1.在application.properties中配置数据源
我们在application.properties的配置中配置了两个数据源,第一个以datasource.primary开头,第二个以datasource.secondary开头。
# 数据库访问配置
# 主数据源,默认的
datasource.primary.type=com.alibaba.druid.pool.DruidDataSource
datasource.primary.driver-class-name=org.postgresql.Driver
datasource.primary.url=jdbc:postgresql://192.168.1.213/test2
datasource.primary.username=postgres
datasource.primary.password=test
# 初始化大小,最小,最大
datasource.primary.initialSize=5
datasource.primary.minIdle=5
datasource.primary.maxActive=30
# 配置获取连接等待超时的时间
datasource.primary.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
datasource.primary.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
datasource.primary.minEvictableIdleTimeMillis=300000
datasource.primary.validationQuery=SELECT 'x'
datasource.primary.testWhileIdle=true
datasource.primary.testOnBorrow=false
datasource.primary.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
datasource.primary.poolPreparedStatements=true
datasource.primary.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
datasource.primary.filters=stat,wall,slf4j
# 合并多个DruidDataSource的监控数据
#datasource.primary.useGlobalDataSourceStat=true
#第二个数据源配置
datasource.secondary.type=com.alibaba.druid.pool.DruidDataSource
datasource.secondary.driver-class-name=com.mysql.jdbc.Driver
datasource.secondary.url=jdbc:mysql://localhost:3306/test
datasource.secondary.username=root
datasource.secondary.password=
# 初始化大小,最小,最大
datasource.secondary.initialSize=5
datasource.secondary.minIdle=5
datasource.secondary.maxActive=30
# 配置获取连接等待超时的时间
datasource.secondary.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
datasource.secondary.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
datasource.secondary.minEvictableIdleTimeMillis=300000
datasource.secondary.validationQuery=SELECT 'x'
datasource.secondary.testWhileIdle=true
datasource.secondary.testOnBorrow=false
datasource.secondary.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
datasource.secondary.poolPreparedStatements=true
datasource.secondary.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
datasource.secondary.filters=stat,wall,slf4j
2. pom.xml的配置
引入druid数据库连接池、mysql、postgresql等jar。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
3. 向Spring容器注册数据源
当存在多于1个数据源的时候,必须选择一个作为主数据源(Primary DataSource),即如果数据库操作没有指明使用哪个数据源的时候,默认使用主数据源。同时,把数据源绑定到不同的JdbcTemplate上。
@Configuration
public class DatasourceConfiguration {
private static final Logger log = LoggerFactory.getLogger(DatasourceConfiguration.class);
@Bean(name = "primaryDataSource")
@Primary
@ConfigurationProperties(prefix = "datasource.primary")
public DataSource primaryDataSource() {
log.info("-------------------- primaryDataSource init ---------------------");
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "datasource.secondary")
public DataSource secondaryDataSource() {
log.info("-------------------- secondaryDataSource init ---------------------");
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
4. 代码中使用多个数据源
@RestController
public class DemoController {
@Resource(name = "primaryJdbcTemplate")
JdbcTemplate jdbcTemplate;
@Resource(name = "secondaryJdbcTemplate")
JdbcTemplate secondaryJdbcTemplate;
@RequestMapping(value = "/hello.do", method = RequestMethod.GET)
public Map<String, String> hello(@RequestParam(value = "id", required = true) Integer id) {
Map<String, String> map = new HashMap<String, String> ();
String username = getNameById(id);
String studentName = getStudentName(id);
map.put("username", username);
map.put("studentName", studentName);
return map;
}
public String getNameById(Integer id) {
String sql = "select username from t_user where id = ? ";
List<String> list = jdbcTemplate.queryForList(sql, new Object[] {id}, String.class);
return list.isEmpty() ? null : list.get(0);
}
public String getStudentName(Integer id) {
String sql = "select student_name from student where student_id = ? ";
List<String> list = secondaryJdbcTemplate.queryForList(sql, new Object[] {id}, String.class);
return list.isEmpty() ? null : list.get(0);
}
}
网友评论