View Javadoc
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   * Provides database connection pooling using HikariCP.
12   */
13  public final class ConnectionProviderPooled implements ConnectionProvider {
14  
15      /**
16       * HikariCP connection pool.
17       */
18      private final HikariDataSource pool;
19  
20      /**
21       * Ensure idempotency of this.close() method.
22       */
23      private final AtomicBoolean isOpen = new AtomicBoolean(true);
24  
25      /**
26       * Constructor.
27       * 
28       * @param url
29       * @param minPoolSize
30       * @param maxPoolSize
31       */
32      public ConnectionProviderPooled(String url, int minPoolSize, int maxPoolSize) {
33          this(createPool(url, null, null, minPoolSize, maxPoolSize));
34      }
35  
36      // Visible for testing
37      ConnectionProviderPooled(HikariDataSource pool) {
38          this.pool = pool;
39      }
40  
41      /**
42       * Constructor.
43       * 
44       * @param url jdbc url
45       * @param username database login username
46       * @param password database login password
47       * @param minPoolSize minimum size of the connection pool
48       * @param maxPoolSize maximum size of the connection pool
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       * Returns a new pooled data source based on jdbc url.
57       * 
58       * @param url jdbc url
59       * @param username login username
60       * @param password login password
61       * @param minPoolSize minimum database connection pool size
62       * @param maxPoolSize maximum database connection pool size
63       * @return
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  }