我正在尝试找出最佳方法,将hikaricp(JDBC连接池)与Microsoft SQL Server配合使用。从我所看到的情况来看,推荐使用DataSource选项(正如我看到的大多数连接池一样)。但是,根据我所看到的示例,我无法正确地与SQL Server数据库建立连接 - 想知道是否有工作示例,我可以将我的数据库信息插入其中。
请确保您已完成以下步骤:
如果使用maven,请确保您的pom文件中包含以下依赖项(如果使用JDK7/8):
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.0.1</version>
<scope>compile</scope>
</dependency>
如果使用其他的构建工具,相应地更改资源URL(或者如果没有其他选项,只需从Maven存储库下载JAR文件)。import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
添加以下最终属性(或者从配置文件中加载它们):
private final String url = "jdbc:sqlserver://";
private final String serverName= "xxx.xxx.xxx.xxx";
private final int portNumber = 1433;
private final String databaseName= "ACTUALDBNAME";
private final String userName = "ACTUALUSERNAME";
private final String password = "ACTUALPASSWORD";
private final String selectMethod = "cursor";
你可以像这样检索连接URL:
public String getConnectionUrl() {
return url+this.serverName+":"+this.portNumber+";databaseName="+this.databaseName+";user="+this.userName+";password="+this.password+";selectMethod="+this.selectMethod+";";
}
接下来,以下内容将为您提供所需的数据源以获取连接:
public DataSource getDataSource() {
final HikariDataSource ds = new HikariDataSource();
ds.setMaximumPoolSize(10);
ds.setDataSourceClassName("com.microsoft.sqlserver.jdbc.SQLServerDataSource");
// ds.addDataSourceProperty("serverName", this.serverName);
//ds.addDataSourceProperty("databaseName", this.databaseName);
ds.addDataSourceProperty("url", this.getConnectionUrl());
ds.addDataSourceProperty("user", this.userName);
ds.addDataSourceProperty("password", this.password);
ds.setInitializationFailFast(true);
ds.setPoolName("wmHikariCp");
return ds;
}
public DataSource getDataSource() {
HikariConfig config = new HikariConfig();
config.setMaximumPoolSize(10);
config.setDataSourceClassName("com.microsoft.sqlserver.jdbc.SQLServerDataSource");
config.addDataSourceProperty("serverName", this.serverName);
config.addDataSourceProperty("port", this.portNumber);
config.addDataSourceProperty("databaseName", this.databaseName);
config.addDataSourceProperty("user", this.userName);
config.addDataSourceProperty("password", this.password);
return new HikariDataSource(config); //pass in HikariConfig to HikariDataSource
}
首选方法是将HikariConfig传递给HikariDataSource构造函数。您也可以从属性文件中加载配置。
然后从数据源获取连接:
Connection con = null;
con = ds.getConnection(); //where ds is the dataSource retrieved from step 5