Esempio n. 1
0
  /**
   * 获得一个数据源
   *
   * @param dsName 数据源名称,若null使用配置文件中的默认连接,此名称在配置文件中定义
   * @param sshName 跳板机名称
   * @throws ConnException
   */
  public static synchronized DataSource getDataSource(String dsName, String sshName)
      throws ConnException {
    if (dbSetting == null) {
      throw new ConnException("No setting found, please init it!");
    }
    DsSetting dsSetting = null;
    try {
      dsSetting = new DsSetting(dsName, sshName, dbSetting);
    } catch (SettingException e) {
      throw new ConnException("Init datasource setting fail!", e);
    }

    // 如果已经存在已有数据源(连接池)直接返回
    DruidDataSource existedDataSource = dsMap.get(dsSetting.getName());
    if (existedDataSource != null) {
      return existedDataSource;
    }

    // 基本连接信息
    String remoteHost = dsSetting.getString(DsSetting.KEY_DS_HOST);
    int port = dsSetting.getInt(DsSetting.KEY_DS_PORT);
    String dbName = dsSetting.getString(DsSetting.KEY_DS_DB);
    // 验证连接信息的有效性
    if (StrUtil.isBlank(remoteHost) || !SocketUtil.isValidPort(port) || StrUtil.isBlank(dbName)) {
      throw new ConnException(
          "Invalid connection info=>host:"
              + remoteHost
              + ", port:"
              + port
              + ", database:"
              + dbName
              + "】");
    }

    DruidDataSource dds = new DruidDataSource();
    if (druidSetting != null) {
      try {
        // 连接池参数注入
        druidSetting.toObject(dds);
      } catch (SettingException e) {
        throw new ConnException("Read Druid setting error!", e);
      }
    }
    // 基本连接信息
    dds.setName(dsSetting.getName()); // 数据源名称为连接名称
    dds.setDriverClassName(dsSetting.getJdbcDriver());
    dds.setUsername(dsSetting.getDsUser());
    dds.setPassword(dsSetting.getDsPass());
    if (dsSetting.isEnableSSH()) {
      port = SSHUtil.openAndBindPortToLocal(dsSetting.getSSHConnector(), remoteHost, port);
      remoteHost = SocketUtil.LOCAL_IP;
    }
    String jdbcUrl =
        DbUtil.buildJdbcUrl(
            dsSetting.getProtocol(), remoteHost, port, dbName, dsSetting.getJdbcUrlParam());
    dds.setUrl(jdbcUrl);
    logger.info("【{}】{}@{}", dsSetting.getName(), dds.getUsername(), jdbcUrl);

    // 添加到数据源池中,以备下次使用
    dsMap.put(dsSetting.getName(), dds);
    return dds;
  }