您好,登錄后才能下訂單哦!
這篇“springboot中如何利用mybatis+druid配置動態數據源”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“springboot中如何利用mybatis+druid配置動態數據源”文章吧。
一、建數據庫和表
1.數據庫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.數據庫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引入包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency> <!-- aop --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> </dependency> <!-- alibaba druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!-- dynamic--> <dependency> <groupId>com.typesafe.dynamicdatasource</groupId> <artifactId>dynamic-data-source_2.11</artifactId> </dependency>
三、用generator插件生成user、role兩張表的實體類、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 #驅動包 driver-class-name: com.mysql.cj.jdbc.Driver #初始連接數 initial-size: 5 #最小空閑數 min-idle: 5 #最大活動數 max-active: 20 #等待超時時間 max-wait: 60000 #配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 time-between-eviction-runs-millis: 60000 # 配置一個連接在池中最小生存的時間,單位是毫秒 min-evictable-idle-time-millis: 300000 #驗證數據庫連接的查詢語句,MYSQL是select 1 validation-query: SELECT 1 FROM DUAL #空閑時測試,testOnBorrow和testOnReturn在生產環境一般是不開啟的,主要是性能考慮。失效連接主要通過testWhileIdle保證 test-while-idle: true test-on-borrow: false test-on-return: false #打開PSCache,并指定每個鏈接上的PSCache大小 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 #配置監控統計攔截的filters,去掉后監控界面sql無法統計,‘wall'用于防火墻,此處是filter修改的地方 filters: stat,wall #通過connectproperties屬性來打開mergesql功能:慢sql記錄 connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #合并多個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 #驅動包 driver-class-name: com.mysql.cj.jdbc.Driver #初始連接數 initial-size: 5 #最小空閑數 min-idle: 5 #最大活動數 max-active: 20 #等待超時時間 max-wait: 60000 #配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 time-between-eviction-runs-millis: 60000 # 配置一個連接在池中最小生存的時間,單位是毫秒 min-evictable-idle-time-millis: 300000 #驗證數據庫連接的查詢語句,MYSQL是select 1 validation-query: SELECT 1 FROM DUAL #空閑時測試,testOnBorrow和testOnReturn在生產環境一般是不開啟的,主要是性能考慮。失效連接主要通過testWhileIdle保證 test-while-idle: true test-on-borrow: false test-on-return: false #打開PSCache,并指定每個鏈接上的PSCache大小 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 #配置監控統計攔截的filters,去掉后監控界面sql無法統計,‘wall'用于防火墻,此處是filter修改的地方 filters: stat,wall #通過connectproperties屬性來打開mergesql功能:慢sql記錄 connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #合并多個DruidDataSource useGlobalDataSourceStat: true
五、啟動類掃描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中的配置導入DataSource中,并注入到bean
@Configuration public class DataSourceConfig { //從配置文件配置數據源 @Primary @Bean(name="datasource1") @ConfigurationProperties("spring.datasource.db1") public DataSource dataSource1(){ return new DruidDataSource(); } //從配置文件配置數據源 @Bean(name="datasource2") @ConfigurationProperties("spring.datasource.db2") public DataSource dataSource2(){ return new DruidDataSource(); } //動態數據源 進行數據源切換 @Bean(name="dynamicDataSource") public DataSource dynamicDataSource(){ DynamicDataSource dynamicDatasource=new DynamicDataSource(); //設置默認數據源 dynamicDatasource.setDefaultTargetDataSource(dataSource1()); //配置多數據源 Map<Object,Object> dsMap=new HashMap<>(); dsMap.put("datasource1",dataSource1()); dsMap.put("datasource2",dataSource2()); //將多數據源放到數據源池中 dynamicDatasource.setTargetDataSources(dsMap); return dynamicDatasource; } }
七、定義動態數據源切換類DynamicDataSourceContextHolder
public class DynamicDataSourceContextHolder { private static final ThreadLocal<String> contextHolder=new ThreadLocal<>(); //設置數據源名稱 public static void setDB(String dbType){ contextHolder.set(dbType); } //獲取數據源名稱 public static String getDB(){ return contextHolder.get(); } //清除數據源名 public static void clearDB(){ contextHolder.remove(); } }
八、定義獲取動態數據源類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);//將動態數據源bean配置到sqlsessionfactory sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); return sqlSessionFactoryBean.getObject(); } @Bean public PlatformTransactionManager platformTransactionManager() { return new DataSourceTransactionManager(dynamicDataSource); } }
十、定義用于切換數據源的注解TargetDataSource
@Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface TargetDataSource { String value() default "datasource1"; }
十一、定義切面DynamicDataSourceAspect,用于攔截注解,并執行數據源切換功能
@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注解,則使用默認數據源,即datasource1 @RequestMapping("/ds1") public String selectDataSource1(){ return userMapper.selectByPrimaryKey(1).toString(); } //使用了注解,則數據源為注解中指定的datasource2 @RequestMapping("/ds2") @TargetDataSource("datasource2") public String selectDataSource2(){ return roleMapper.selectByPrimaryKey(1).toString(); } }
測試
1.輸入
http://localhost:8088/ds1
返回
↓
2.輸入
http://localhost:8088/ds2
返回
↓
以上就是關于“springboot中如何利用mybatis+druid配置動態數據源”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。