使用多数据源配置多个HikariCP数据库连接池
@Bean(name = ETERNAL_DB)
public DataSource eternalDataSource(HikariProperties properties) {
HikariDataSource dataSource = DataSourceBuilder.create()
.url("jdbc:mysql://xx.xx.xx.xx/dbName")
.username("xxx")
.password("xxx")
.driverClassName("com.mysql.jdbc.Driver")
.type(HikariDataSource.class)
.build();
return properties.setAttributeToDataSource(dataSource);
}
HikariProperties中的代码
@Configuration
public class HikariProperties {
private static final int IDLE_TIMEOUT = 60000;
private static final int MAX_POOL_SIZE = 50;
private static final int MINIMUM_POOL_SIZE = 5;
private static final int MAX_LIFTTIME = 120000;
private static final int CONNECTION_TIMEOUT = 20000;
private static final String DATASOURCE_CLASS_NAME = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource";
public HikariDataSource setAttributeToDataSource(HikariDataSource hikariDataSource) {
hikariDataSource.setDataSourceClassName(DATASOURCE_CLASS_NAME);
hikariDataSource.setConnectionTimeout(CONNECTION_TIMEOUT);
//连接空闲生命周期设置
hikariDataSource.setIdleTimeout(IDLE_TIMEOUT);
hikariDataSource.setMinimumPoolSize(MINIMUM_POOL_SIZE);
hikariDataSource.setMaximumPoolSize(MAX_POOL_SIZE);
//检查空余连接优化连接池设置时间,单位毫秒
hikariDataSource.setMaxLifetime(MAX_LIFTTIME);
hikariDataSource.setConnectionTestQuery("SELECT 1");
return hikariDataSource;
}
}
然后就报错
### Cause: java.sql.SQLException: No database selected
; uncategorized SQLException; SQL state [3D000]; error code [1046]; No database selected; nested exception is java.sql.SQLException: No database selected] with root cause
java.sql.SQLException: No database selected
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
改了一下 改成这样就没问题了
改了eternalDataSource的建立DataSource方式
@Bean(name = ETERNAL_DB)
public DataSource statisticsDataSource() {
String url = "jdbc:mysql://xx.xx.xx.xx/dbName";
String user = "xxx";
String passWord = "xxx"
String dbEncoding = ConfigHelper.getMysqlEncoding();
HikariConfig config = new HikariConfig();
config.setMaximumPoolSize(4);
config.setMinimumPoolSize(2);
config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
config.addDataSourceProperty("url", url);
config.addDataSourceProperty("encoding", dbEncoding);
config.addDataSourceProperty("noAccessToProcedureBodies", "true");
config.addDataSourceProperty("user", user);
config.addDataSourceProperty("password", passWord);
return new HikariDataSource(config);
}
到底我上面的写法哪里有问题啊 ,求高人指点吧
很迷