1 package com.github.davidmoten.rx.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.SQLException;
5 import java.util.concurrent.atomic.AtomicBoolean;
6
7 import com.github.davidmoten.rx.jdbc.exceptions.SQLRuntimeException;
8 import com.zaxxer.hikari.HikariDataSource;
9
10
11
12
13 public final class ConnectionProviderPooled implements ConnectionProvider {
14
15
16
17
18 private final HikariDataSource pool;
19
20
21
22
23 private final AtomicBoolean isOpen = new AtomicBoolean(true);
24
25
26
27
28
29
30
31
32 public ConnectionProviderPooled(String url, int minPoolSize, int maxPoolSize) {
33 this(createPool(url, null, null, minPoolSize, maxPoolSize));
34 }
35
36
37 ConnectionProviderPooled(HikariDataSource pool) {
38 this.pool = pool;
39 }
40
41
42
43
44
45
46
47
48
49
50 public ConnectionProviderPooled(String url, String username, String password, int minPoolSize,
51 int maxPoolSize) {
52 this(createPool(url, username, password, minPoolSize, maxPoolSize));
53 }
54
55
56
57
58
59
60
61
62
63
64
65 private static HikariDataSource createPool(String url, String username, String password,
66 int minPoolSize, int maxPoolSize) {
67
68 HikariDataSource ds = new HikariDataSource();
69 ds.setJdbcUrl(url);
70 ds.setUsername(username);
71 ds.setPassword(password);
72 ds.setMinimumIdle(minPoolSize);
73 ds.setMaximumPoolSize(maxPoolSize);
74 return ds;
75 }
76
77 @Override
78 public Connection get() {
79 try {
80 return pool.getConnection();
81 } catch (SQLException e) {
82 throw new SQLRuntimeException(e);
83 }
84 }
85
86 @Override
87 public void close() {
88 if (isOpen.getAndSet(false))
89 pool.close();
90 }
91
92 }