DruidDataSourceFactory创建for循环多个数据源,并连接到指定的数据源上
时间: 2024-03-01 19:55:44 浏览: 52
DruidDataSourceFactory是Druid提供的数据源工厂类,可以用于创建并配置Druid数据源。要创建多个数据源,可以使用for循环来重复创建并配置多个Druid数据源,代码示例如下:
```java
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
public class MultiDataSourceUtil {
private static final String DB_DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
private static final String DB_URL_TEMPLATE = "jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true&useSSL=false";
private static final String DB_USER_NAME = "root";
private static final String DB_PASSWORD = "123456";
public static Map<String, DataSource> createDataSources() {
Map<String, DataSource> dataSourceMap = new HashMap<>();
for (int i = 0; i < 3; i++) {
String dbName = "db_" + i;
String url = String.format(DB_URL_TEMPLATE, "localhost", "3306", dbName);
DruidDataSource dataSource = createDataSource(url);
dataSourceMap.put(dbName, dataSource);
}
return dataSourceMap;
}
private static DruidDataSource createDataSource(String url) {
try {
DruidDataSource dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(getDataSourceProperties(url));
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestWhileIdle(true);
dataSource.setTestOnBorrow(false);
dataSource.setTestOnReturn(false);
dataSource.setPoolPreparedStatements(true);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
return dataSource;
} catch (Exception e) {
throw new RuntimeException("Create data source error", e);
}
}
private static Properties getDataSourceProperties(String url) {
Properties properties = new Properties();
properties.setProperty(DruidDataSourceFactory.PROP_DRIVERCLASSNAME, DB_DRIVER_CLASS_NAME);
properties.setProperty(DruidDataSourceFactory.PROP_URL, url);
properties.setProperty(DruidDataSourceFactory.PROP_USERNAME, DB_USER_NAME);
properties.setProperty(DruidDataSourceFactory.PROP_PASSWORD, DB_PASSWORD);
return properties;
}
}
```
在上面的代码中,我们使用for循环创建了3个MySQL数据源,分别对应数据库db_0、db_1、db_2。在createDataSource方法中,我们对Druid数据源进行了一些常用的配置,例如设置连接池大小、开启SQL预编译等。最后,我们将所有的数据源保存到一个Map中,并以数据库名作为key。这样我们就可以根据需要从Map中获取对应的数据源,连接到指定的数据源上进行查询或更新操作。
阅读全文