读目录
背景
如何使用druid 连接池配置多个数据源
参考文档:
回到顶部
目录结构
为了更好的区分,我把不同的数据库,新建在不同的目录下面
先看目录结构:
修改配置
pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.13</version>
</dependency>
修改application.yml配
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
# Druid连接池配置
druid:
# 初始化大小,最小,最大
initial-size: 5
max-active: 30
min-idle: 5
# 获取数据库连接等待的超时时间
max-wait: 3000
max-open-prepared-statements: -1
# 配置多久进行一次检测,检测需要关闭的空闲连接 单位毫秒
time-between-eviction-runs-millis: 60000
# 配置连接在池中的最小生存时间
min-evictable-idle-time-millis: 300000
# 配置连接在池中的最大生存时间
max-evictable-idle-time-millis: 400000
# 系统启动时通过该sql语句验证数据库是否可用,如果不配置validationQuery,则下面三项无效
validation-query: SELECT 1
# 启用空闲连接检测,以便回收
test-while-idle: true
# 从连接池获取连接时,是否检测连接可用性,开启性能会有些许影响
test-on-borrow: false
# 释放连接到连接池时,是否检测连接可用性,开启性能会有些许影响
test-on-return: false
# 打开PSCache,并且指定每个连接上PSCache的大小
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
use-global-data-source-stat: true
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
server:
port: 7080
mybatis:
# 对应实体类的包名
type-aliases-package: com.example.druiddemo.dao
mapper-locations: classpath:mybatis/mapper/*.xml
# config-location: classpath:mybatis/mybatis-config.xml
mfw:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/mfw?characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
komo:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/komo?characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
修改config目录下的配置
KomoDataSourceConfig.java
package com.example.druiddemo.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
/**
* @author komiles@163.com
* @date 2020-05-12 18:41
*/
@Configuration
@MapperScan(basePackages = KomoDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "komoSqlSessionFactory")
public class KomoDataSourceConfig {
/**
* 配置多数据源 关键就在这里 这里配置了不同的数据源扫描不同mapper
*/
static final String PACKAGE = "com.example.druiddemo.mapper.komo";
static final String MAPPER_LOCATION = "classpath:mybatis/komo/mapper/*.xml";
/**
* 连接数据库信息 这个其实更好的是用配置中心完成
*/
@Value("${komo.datasource.url}")
private String url;
@Value("${komo.datasource.username}")
private String username;
@Value("${komo.datasource.password}")
private String password;
@Value("${komo.datasource.driver-class-name}")
private String driverClassName;
@Bean
public ServletRegistrationBean druidServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// IP白名单
servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
// IP黑名单(共同存在时,deny优先于allow)
// servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
//控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "admin");
//是否能够重置数据 禁用HTML页面上的“Reset All”功能
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
// 注解@Primary表示是主数据源
@Bean("komoDataSource")
@Primary
public DataSource komoDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
return dataSource;
}
@Bean(name = "komoTransactionManager")
@Primary
public DataSourceTransactionManager masterTransactionManager() {
return new DataSourceTransactionManager(komoDataSource());
}
@Bean(name = "komoSqlSessionFactory")
@Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("komoDataSource") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(KomoDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
MfwDataSourceConfig.java
package com.example.druiddemo.config;
import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
/**
* @author komiles@163.com
* @date 2020-05-12 18:41
*/
@Configuration
@MapperScan(basePackages = MfwDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "mfwSqlSessionFactory")
public class MfwDataSourceConfig {
/**
* 配置多数据源 关键就在这里 这里配置了不同的数据源扫描不同mapper
*/
static final String PACKAGE = "com.example.druiddemo.mapper.mfw";
static final String MAPPER_LOCATION = "classpath:mybatis/mfw/mapper/*.xml";
/**
* 连接数据库信息 这个其实更好的是用配置中心完成
*/
@Value("${mfw.datasource.url}")
private String url;
@Value("${mfw.datasource.username}")
private String username;
@Value("${mfw.datasource.password}")
private String password;
@Value("${mfw.datasource.driver-class-name}")
private String driverClassName;
@Bean("mfwDataSource")
public DataSource mfwDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
return dataSource;
}
@Bean(name = "mfwTransactionManager")
public DataSourceTransactionManager masterTransactionManager() {
return new DataSourceTransactionManager(mfwDataSource());
}
@Bean(name = "mfwSqlSessionFactory")
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("mfwDataSource") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MfwDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
UserController.java
package com.example.druiddemo.controller;
import com.example.druiddemo.common.PageDTO;
import com.example.druiddemo.dao.komo.User;
import com.example.druiddemo.dao.mfw.BaseUser;
import com.example.druiddemo.service.BaseUserService;
import com.example.druiddemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author komiles@163.com
* @date 2020-04-30 18:47
*/
@RequestMapping("/user")
@RestController
public class UserController {
@Autowired
private UserService userService;
@Autowired
private BaseUserService baseUserService;
@GetMapping("/one")
public User getOne(@RequestParam("id") Integer id){
return userService.getOne(id);
}
@GetMapping("/list")
public PageDTO<User> getList(@RequestParam(value = "page",defaultValue = "1") Integer page,
@RequestParam(value = "limit",defaultValue = "10") Integer limit){
return userService.getList(page,limit);
}
@GetMapping("/base")
public BaseUser getBase(@RequestParam("id") Integer id){
return baseUserService.getOne(id);
}
}
启动类Application修改
package com.example.druiddemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
// 去掉自动数据库自动配置类
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DruidDemoApplication {
public static void main(String[] args) {
SpringApplication.run(DruidDemoApplication.class, args);
System.out.println("============= druid-demo application start =============");
}
}
演示效果
http://127.0.0.1:7080/user/one?id=1
http://127.0.0.1:7080/user/base?id=1
http://localhost:7080/druid/index.html
http://localhost:7080/druid/weburi.html
代码地址
https://github.com/KoMiles/spring-example/tree/master/druid-demo
千里之行,始于足下。改变现在,就是改变未来。改变未来,从现在开始。