DataSourcePool.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.yihu.ehr.util.db;
  2. import org.apache.commons.dbcp2.DriverManagerConnectionFactory;
  3. import org.apache.commons.dbcp2.PoolableConnection;
  4. import org.apache.commons.dbcp2.PoolableConnectionFactory;
  5. import org.apache.commons.dbcp2.PoolingDataSource;
  6. import org.apache.commons.pool2.impl.GenericObjectPool;
  7. import javax.sql.DataSource;
  8. /**
  9. * Created by Air on 2015/5/28.
  10. */
  11. public class DataSourcePool {
  12. public static final String JDBC_MYSQL = "jdbc:mysql";
  13. public static final String JDBC_ORACLE = "jdbc:oracle";
  14. public static final String JDBC_MICROSOFT_SQLSERVER = "jdbc:microsoft:sqlserver";
  15. public static final String COM_MYSQL_JDBC_DRIVER = "com.mysql.jdbc.Driver";
  16. public static final String ORACLE_JDBC_DRIVER_ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
  17. public static final String COM_MICROSOFT_JDBC_SQLSERVER_DRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
  18. private DriverManagerConnectionFactory connectionFactory;
  19. private PoolableConnectionFactory poolableConnectionFactory;
  20. private GenericObjectPool<PoolableConnection> connectionPool;
  21. private String uri;
  22. public DataSourcePool(String uri) {
  23. this.uri = uri;
  24. registerDriver();
  25. connectionFactory = new DriverManagerConnectionFactory(this.uri, null);
  26. poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
  27. connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
  28. poolableConnectionFactory.setPool(connectionPool);
  29. }
  30. public DataSource getDataSource() {
  31. return new PoolingDataSource<>(connectionPool);
  32. }
  33. public void registerDriver() {
  34. try {
  35. Class.forName(getDriver());
  36. } catch (ClassNotFoundException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. public String getDriver() {
  41. if (this.uri.contains(JDBC_MYSQL)) {
  42. return COM_MYSQL_JDBC_DRIVER;
  43. } else if (this.uri.contains(JDBC_ORACLE)) {
  44. return ORACLE_JDBC_DRIVER_ORACLE_DRIVER;
  45. } else if (this.uri.contains(JDBC_MICROSOFT_SQLSERVER)) {
  46. return COM_MICROSOFT_JDBC_SQLSERVER_DRIVER;
  47. }
  48. return null;
  49. }
  50. }