文章來源:https://www.cnblogs.com/wangkongming/p/12878221.html
读目录
- 背景
- 目录结构
- 修改配置
- 演示效果
- 代码地址
回到顶部
背景
如何使用druid 连接池配置多个数据源
参考文档:https://www.cnblogs.com/qdhxhz/p/10192041.html
回到顶部
目录结构
为了更好的区分,我把不同的数据库,新建在不同的目录下面
先看目录结构:
回到顶部
修改配置
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: 5max-active: 30min-idle: 5# 获取数据库连接等待的超时时间max-wait: 3000max-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: falsemax-pool-prepared-statement-per-connection-size: 20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filters: stat,walluse-global-data-source-stat: true# 通过connectProperties属性来打开mergeSql功能;慢SQL记录connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000server:port: 7080mybatis:# 对应实体类的包名type-aliases-package: com.example.druiddemo.daomapper-locations: classpath:mybatis/mapper/*.xml
# config-location: classpath:mybatis/mybatis-config.xmlmfw:datasource:username: rootpassword: 123456url: jdbc:mysql://127.0.0.1:3306/mfw?characterEncoding=utf-8driver-class-name: com.mysql.jdbc.Driver
komo:datasource:username: rootpassword: 123456url: jdbc:mysql://127.0.0.1:3306/komo?characterEncoding=utf-8driver-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;@Beanpublic 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;}@Beanpublic 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")@Primarypublic DataSource komoDataSource(){DruidDataSource dataSource = new DruidDataSource();dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);dataSource.setDriverClassName(driverClassName);return dataSource;}@Bean(name = "komoTransactionManager")@Primarypublic DataSourceTransactionManager masterTransactionManager() {return new DataSourceTransactionManager(komoDataSource());}@Bean(name = "komoSqlSessionFactory")@Primarypublic 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 {@Autowiredprivate UserService userService;@Autowiredprivate 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
千里之行,始于足下。改变现在,就是改变未来。改变未来,从现在开始。 个人网站:http://www.wangkongming.cn