连接到不同服务器中的许多数据库

Connect to many databases in different servers

之前可能有人问过这个问题,但我还没找到。

我的问题很简单,我想验证与大量数据库的连接。我在 Java(我正在使用 Spring)中创建了一个进程,该进程与从查询中获得的一些数据创建数据源连接。我只想知道是否有更好的方法或更快的方法。我的过程需要花费大量时间来验证整个连接(接近 ​​5K)。

这就是我的代码的样子

public void validateConnections() throws IllegalBlockSizeException, BadPaddingException {
    BasicDataSource dataSource;

    List<Element> elements = dataToCreateDatasourcesRepository.getAllDatas();

    for(Element element : elements) {
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName(Constants.DRIVER_CLASS_NAME_PROP);
        dataSource.setUrl(getConnectionUrl(element.getElementNbr(), element.getCode()));
        dataSource.setUsername(userName);
        dataSource.setPassword(EncryptionAlgorithm.decryptFromHex(password));
        try {
          Connection conn = dataSource.getConnection();
          Statement stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery(query);
          if(rs == null || !rs.next()) {
            LOG
                .info(
                    "Connection for element [" + element.getElementNbr() + "]." + element.getCode() + " UNSUCCESSFULY ");
          }
          else {
            LOG.info("Connection for element [" + element.getElementNbr() + "]." + element.getCode() + " SUCCESSFULY ");
          }
        }
        catch(Exception e) {
          LOG.info("Connection for element [" + element.getElementNbr() + "]." + element.getCode() + " UNSUCCESSFULY ");
          LOG.error(e);
        }
      }
  }

  public String getConnectionUrl(String elementNbr, String code) {
    return String
        .format(
            dbUrl,
            PREFIX.concat(elementNbr.toString()),
            code.concat(Constants.HOSTNAME),
            PREFIX.concat(elementNbr.toString()),
            code.toLowerCase());
  }

建立连接是, which takes a lot of time on the server side. You're running a single loop which most likely stays idle waiting for the next connection. You may try using a thread pool executor并行发送多个连接。

附带说明一下,您可能还想使用 try-with-resources 语句来自动关闭结果集、语句和连接。