今天就跟大家聊聊有關(guān)springboot中怎么利用mybatis+druid配置動(dòng)態(tài)數(shù)據(jù)源,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
創(chuàng)新互聯(lián)建站-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比同江網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式同江網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋同江地區(qū)。費(fèi)用合理售后完善,十年實(shí)體公司更值得信賴。
一、建數(shù)據(jù)庫和表
1.數(shù)據(jù)庫demo1放一張user表
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'aa'); INSERT INTO `user` VALUES ('2', 'bb');
2.數(shù)據(jù)庫demo2放一張role表
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for role -- ---------------------------- DROP TABLE IF EXISTS `role`; CREATE TABLE `role` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of role -- ---------------------------- INSERT INTO `role` VALUES ('1', 'CC'); INSERT INTO `role` VALUES ('2', 'DD');
二、pom.xml引入包
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-thymeleaf MySQL mysql-connector-java runtime mysql mysql-connector-java org.springframework.boot spring-boot-starter-jdbc org.mybatis.spring.boot mybatis-spring-boot-starter 2.0.1 org.aspectj aspectjweaver com.alibaba druid-spring-boot-starter 1.1.10 com.typesafe.dynamicdatasource dynamic-data-source_2.11
三、用generator插件生成user、role兩張表的實(shí)體類、mapper.java、mapper.xml
User.java Role.java UserMapper.java RoleMapper.java UserMapper.xml RoleMapper.xml
四、配置application.yml
server: port: 8088 mybatis: mapper-locations: classpath:mapper/*.xml spring: datasource: db1: url: jdbc:mysql://localhost:3306/demo1?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT username: root password: root type: com.alibaba.druid.pool.DruidDataSource #驅(qū)動(dòng)包 driver-class-name: com.mysql.cj.jdbc.Driver #初始連接數(shù) initial-size: 5 #最小空閑數(shù) min-idle: 5 #最大活動(dòng)數(shù) max-active: 20 #等待超時(shí)時(shí)間 max-wait: 60000 #配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒 time-between-eviction-runs-millis: 60000 # 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒 min-evictable-idle-time-millis: 300000 #驗(yàn)證數(shù)據(jù)庫連接的查詢語句,MYSQL是select 1 validation-query: SELECT 1 FROM DUAL #空閑時(shí)測試,testOnBorrow和testOnReturn在生產(chǎn)環(huán)境一般是不開啟的,主要是性能考慮。失效連接主要通過testWhileIdle保證 test-while-idle: true test-on-borrow: false test-on-return: false #打開PSCache,并指定每個(gè)鏈接上的PSCache大小 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 #配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計(jì),‘wall'用于防火墻,此處是filter修改的地方 filters: stat,wall #通過connectproperties屬性來打開mergesql功能:慢sql記錄 connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #合并多個(gè)DruidDataSource useGlobalDataSourceStat: true db2: url: jdbc:mysql://localhost:3306/demo2?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT username: root password: root type: com.alibaba.druid.pool.DruidDataSource #驅(qū)動(dòng)包 driver-class-name: com.mysql.cj.jdbc.Driver #初始連接數(shù) initial-size: 5 #最小空閑數(shù) min-idle: 5 #最大活動(dòng)數(shù) max-active: 20 #等待超時(shí)時(shí)間 max-wait: 60000 #配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒 time-between-eviction-runs-millis: 60000 # 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒 min-evictable-idle-time-millis: 300000 #驗(yàn)證數(shù)據(jù)庫連接的查詢語句,MYSQL是select 1 validation-query: SELECT 1 FROM DUAL #空閑時(shí)測試,testOnBorrow和testOnReturn在生產(chǎn)環(huán)境一般是不開啟的,主要是性能考慮。失效連接主要通過testWhileIdle保證 test-while-idle: true test-on-borrow: false test-on-return: false #打開PSCache,并指定每個(gè)鏈接上的PSCache大小 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 #配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計(jì),‘wall'用于防火墻,此處是filter修改的地方 filters: stat,wall #通過connectproperties屬性來打開mergesql功能:慢sql記錄 connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #合并多個(gè)DruidDataSource useGlobalDataSourceStat: true
五、啟動(dòng)類掃描mapper.java文件
@SpringBootApplication @MapperScan("com.example.demo.dao") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
六、定義DataSourceConfig, 將application.yml中的配置導(dǎo)入DataSource中,并注入到bean
@Configuration public class DataSourceConfig { //從配置文件配置數(shù)據(jù)源 @Primary @Bean(name="datasource1") @ConfigurationProperties("spring.datasource.db1") public DataSource dataSource1(){ return new DruidDataSource(); } //從配置文件配置數(shù)據(jù)源 @Bean(name="datasource2") @ConfigurationProperties("spring.datasource.db2") public DataSource dataSource2(){ return new DruidDataSource(); } //動(dòng)態(tài)數(shù)據(jù)源 進(jìn)行數(shù)據(jù)源切換 @Bean(name="dynamicDataSource") public DataSource dynamicDataSource(){ DynamicDataSource dynamicDatasource=new DynamicDataSource(); //設(shè)置默認(rèn)數(shù)據(jù)源 dynamicDatasource.setDefaultTargetDataSource(dataSource1()); //配置多數(shù)據(jù)源 Map
七、定義動(dòng)態(tài)數(shù)據(jù)源切換類DynamicDataSourceContextHolder
public class DynamicDataSourceContextHolder { private static final ThreadLocalcontextHolder=new ThreadLocal<>(); //設(shè)置數(shù)據(jù)源名稱 public static void setDB(String dbType){ contextHolder.set(dbType); } //獲取數(shù)據(jù)源名稱 public static String getDB(){ return contextHolder.get(); } //清除數(shù)據(jù)源名 public static void clearDB(){ contextHolder.remove(); } }
八、定義獲取動(dòng)態(tài)數(shù)據(jù)源類DynamicDataSource
public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DynamicDataSourceContextHolder.getDB(); } }
九、定義mybatis配置類,將DynamicDataSource放入SqlSessionFactoryBean中
@EnableTransactionManagement @Configuration public class MyBatisConfig { @Resource(name = "dynamicDataSource") private DataSource dynamicDataSource; @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dynamicDataSource);//將動(dòng)態(tài)數(shù)據(jù)源bean配置到sqlsessionfactory sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); return sqlSessionFactoryBean.getObject(); } @Bean public PlatformTransactionManager platformTransactionManager() { return new DataSourceTransactionManager(dynamicDataSource); } }
十、定義用于切換數(shù)據(jù)源的注解TargetDataSource
@Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface TargetDataSource { String value() default "datasource1"; }
十一、定義切面DynamicDataSourceAspect,用于攔截注解,并執(zhí)行數(shù)據(jù)源切換功能
@Aspect @Component public class DynamicDataSourceAspect { @Before("@annotation(targetDataSource)") public void beforeSwitchDS(JoinPoint point,TargetDataSource targetDataSource){ DynamicDataSourceContextHolder.setDB(targetDataSource.value()); } @After("@annotation(targetDataSource)") public void afterSwitchDS(JoinPoint point,TargetDataSource targetDataSource){ DynamicDataSourceContextHolder.clearDB(); } }
十二、測試類Test
@RestController public class Test { @Autowired private RoleMapper roleMapper; @Autowired private UserMapper userMapper; //未使用TargetDataSource注解,則使用默認(rèn)數(shù)據(jù)源,即datasource1 @RequestMapping("/ds1") public String selectDataSource1(){ return userMapper.selectByPrimaryKey(1).toString(); } //使用了注解,則數(shù)據(jù)源為注解中指定的datasource2 @RequestMapping("/ds2") @TargetDataSource("datasource2") public String selectDataSource2(){ return roleMapper.selectByPrimaryKey(1).toString(); } }
測試
1.輸入
http://localhost:8088/ds1
返回
↓
2.輸入
http://localhost:8088/ds2
返回
↓
看完上述內(nèi)容,你們對springboot中怎么利用mybatis+druid配置動(dòng)態(tài)數(shù)據(jù)源有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。