/** {@inheritDoc} */
  public void init() throws ServerInitException {
    try {
      LOGGER.info("正在初始化数据库连接池...");
      Properties prop = loadJdbcProperties();
      dataSource = new ComboPooledDataSource();
      dataSource.setDriverClass(prop.getProperty(DRIVER_PROP));
      dataSource.setJdbcUrl(prop.getProperty(URL_PROP));
      dataSource.setUser(prop.getProperty(USERNAME_PROP));
      dataSource.setPassword(prop.getProperty(PASSWORD_PROP));
      dataSource.setCheckoutTimeout(
          StringUtils.parseInt(prop.getProperty(MAXWAIT_PROP), DEFAULT_MAXWAIT_TIME));
      dataSource.setMaxPoolSize(30);
      dataSource.setInitialPoolSize(10);

      testConnection(dataSource);
      LOGGER.info("初始化数据库连接池成功!");
    } catch (IOException e) {
      throw new ServerInitException("初始化数据库连接池失败!", e);
    } catch (PropertyVetoException e) {
      throw new ServerInitException("初始化数据库连接池失败!", e);
    }
  }
Esempio n. 2
0
  /** 构造. */
  public DataBaseHandle(
      String driver, String url, String user, String password, Integer maxPoolSize) {
    try {
      // 创建连接池
      cpds = new ComboPooledDataSource();

      // 用户设置
      cpds.setDriverClass(driver); // 驱动
      cpds.setJdbcUrl(url); // 连接字符串
      cpds.setUser(user); // 用户名
      cpds.setPassword(password); // 密码
      cpds.setMaxPoolSize(maxPoolSize); // 连接池中保留的最大连接数(默认:15)

      // 默认设置
      cpds.setMinPoolSize(1); // 连接池中保留的最小连接数(默认:0)
      cpds.setInitialPoolSize(1); // 初始化时获取几个连接,取值应在minPoolSize与maxPoolSize之间(默认:3)
      cpds.setAcquireIncrement(1); // 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数(默认:3)
      cpds.setCheckoutTimeout(
          1000); // 当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待,单位毫秒(默认:0)
      cpds.setMaxIdleTime(25000); // 最大空闲时间,定义多少秒内未使用则连接被丢弃,若为0则永不丢弃(默认:0)
      cpds.setIdleConnectionTestPeriod(18000); // 隔多少秒检查所有连接池中的空闲连接,0表示不检查(默认:0)
      cpds.setDebugUnreturnedConnectionStackTraces(
          true); // 启用之后(true),对于每个从连接池拿出去的数据库连接,如果一段时间(unreturnedConnectionTimeout)内没有归还,C3P0就会强制关闭这个连接,并将获取连接时的stack trace,以抛出异常的方式显示出来(默认:false)
      cpds.setUnreturnedConnectionTimeout(
          600); // 用于设置开启debugUnreturnedConnectionStackTraces后的超时时间(单位:秒)
      cpds.setTestConnectionOnCheckin(true); // 如果设为true那么在取得连接的同时将校验连接的有效性(默认:false)
      cpds.setMaxStatements(
          100); // JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量,但由于预缓存的statements属于单个connection而不是整个连接池,所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭(默认:0)
      cpds.setAutomaticTestTable(
          "T_TEST_C3P0"); // c3p0将建一张名为T_TEST_C3P0的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试使用(默认: null)

      // 取连接(测试)
      cpds.getConnection().close();
    } catch (Throwable e) {
      throw new RuntimeException("连接池创建失败", e);
    }
  }
Esempio n. 3
0
  /**
   * Detects changes and reconfigures this dbConfig. Returns true if the database was configured
   * (Config info present. An exception is throwns if the config process fails.
   */
  protected boolean configure() {

    // prefix used before all properties when loafing config. default is 'db'
    String propsPrefix;
    if (defaultDbConfigName.equals(dbConfigName)) {
      propsPrefix = "db";
    } else {
      propsPrefix = "db_" + dbConfigName;
    }

    boolean dbConfigured = false;

    if (changed(propsPrefix)) {
      try {

        // We now know that we will either config the db, or fail with exception
        dbConfigured = true;

        Properties p = Play.configuration;

        if (datasource != null) {
          destroy();
        }

        if (p.getProperty(propsPrefix, "").startsWith("java:")) {

          Context ctx = new InitialContext();
          datasource = (DataSource) ctx.lookup(p.getProperty(propsPrefix));

        } else {

          // Try the driver
          String driver = p.getProperty(propsPrefix + ".driver");
          try {
            Driver d = (Driver) Class.forName(driver, true, Play.classloader).newInstance();
            DriverManager.registerDriver(new ProxyDriver(d));
          } catch (Exception e) {
            throw new Exception("Driver not found (" + driver + ")");
          }

          // Try the connection
          Connection fake = null;
          try {
            if (p.getProperty(propsPrefix + ".user") == null) {
              fake = DriverManager.getConnection(p.getProperty(propsPrefix + ".url"));
            } else {
              fake =
                  DriverManager.getConnection(
                      p.getProperty(propsPrefix + ".url"),
                      p.getProperty(propsPrefix + ".user"),
                      p.getProperty(propsPrefix + ".pass"));
            }
          } finally {
            if (fake != null) {
              fake.close();
            }
          }

          ComboPooledDataSource ds = new ComboPooledDataSource();
          ds.setDriverClass(p.getProperty(propsPrefix + ".driver"));
          ds.setJdbcUrl(p.getProperty(propsPrefix + ".url"));
          ds.setUser(p.getProperty(propsPrefix + ".user"));
          ds.setPassword(p.getProperty(propsPrefix + ".pass"));
          ds.setAcquireRetryAttempts(10);
          ds.setCheckoutTimeout(
              Integer.parseInt(p.getProperty(propsPrefix + ".pool.timeout", "5000")));
          ds.setBreakAfterAcquireFailure(false);
          ds.setMaxPoolSize(Integer.parseInt(p.getProperty(propsPrefix + ".pool.maxSize", "30")));
          ds.setMinPoolSize(Integer.parseInt(p.getProperty(propsPrefix + ".pool.minSize", "1")));
          ds.setMaxIdleTimeExcessConnections(
              Integer.parseInt(
                  p.getProperty(propsPrefix + ".pool.maxIdleTimeExcessConnections", "0")));
          ds.setIdleConnectionTestPeriod(10);
          ds.setTestConnectionOnCheckin(true);
          datasource = ds;
          url = ds.getJdbcUrl();
          Connection c = null;
          try {
            c = ds.getConnection();
          } finally {
            if (c != null) {
              c.close();
            }
          }
          Logger.info("Connected to %s", ds.getJdbcUrl());
        }

        destroyMethod = p.getProperty(propsPrefix + ".destroyMethod", "");

      } catch (Exception e) {
        datasource = null;
        Logger.error(
            e,
            "Cannot connected to the database" + getConfigInfoString() + " : %s",
            e.getMessage());
        if (e.getCause() instanceof InterruptedException) {
          throw new DatabaseException(
              "Cannot connected to the database"
                  + getConfigInfoString()
                  + ". Check the configuration.",
              e);
        }
        throw new DatabaseException(
            "Cannot connected to the database" + getConfigInfoString() + ", " + e.getMessage(), e);
      }
    }

    return dbConfigured;
  }
Esempio n. 4
0
 public void setCheckoutTimeout(int checkoutTimeout) throws NamingException {
   combods.setCheckoutTimeout(checkoutTimeout);
   rebind();
 }