SpringBoot+MybatisPlus+jdbc連接池配置多數(shù)據(jù)源的實現(xiàn)
上pom.xml文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>spring-dataSource</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-dataSource</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.SR5</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.1.8</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
目錄結構
application.xml的結構
server: port: 9086 spring: datasource: #database primary: # 3.0 Datasource jdbc-url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&autoReconnect=true&zeroDateTimeBehavior=convertToNull username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver secondary: # 2.0 Datasource jdbc-url: jdbc:mysql://localhost:3306/user02?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&autoReconnect=true&zeroDateTimeBehavior=convertToNull username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver application: name: lixiaolong #mybatis mybatis-plus: mapper-locations: classpath:/mapper/*Mapper.xml #實體掃描,多個package用逗號或者分號分隔 typeAliasesPackage: com.example.demo.entity; global-config: #主鍵類型 0:"數(shù)據(jù)庫ID自增", 1:"用戶輸入ID",2:"全局唯一ID (數(shù)字類型唯一ID)", 3:"全局唯一ID UUID"; id-type: 0 #字段策略 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷" field-strategy: 2 #駝峰下劃線轉換 db-column-underline: true #刷新mapper 調試神器 refresh-mapper: true #數(shù)據(jù)庫大寫下劃線轉換 #capital-mode: true logic-delete-value: -1 logic-not-delete-value: 0 configuration: map-underscore-to-camel-case: true cache-enabled: false call-setters-on-nulls: true
重要組成部分
1.數(shù)據(jù)源注解以及aop配置
一.
@Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DataSource { DataSourceEnum value() default DataSourceEnum.DB1; }
二.
@Component @Slf4j @Aspect @Order(-1) public class DataSourceAspect { @Pointcut("@within(com.example.demo.annotation.DataSource) || @annotation(com.example.demo.annotation.DataSource)") public void pointCut(){ } @Before("pointCut() && @annotation(dataSource)") public void doBefore(DataSource dataSource){ // log.info("選擇數(shù)據(jù)源---"+dataSource.value().getValue()); DataSourceContextHolder.setDataSource(dataSource.value().getValue()); } @After("pointCut()") public void doAfter(){ DataSourceContextHolder.clear(); } }
mybatisplus動態(tài)數(shù)據(jù)源的配置
一.mybatisplus動態(tài)數(shù)據(jù)源配置類
@Configuration // 注解到spring容器中 @MapperScan(basePackages = "com.example.demo.mapper*") public class MybatisDataSource { /* * 分頁插件,自動識別數(shù)據(jù)庫類型 多租戶,請參考官網(wǎng)【插件擴展】 */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); // 開啟 PageHelper 的支持 paginationInterceptor.setLocalPage(true); return paginationInterceptor; } /** * SQL執(zhí)行效率插件 */ @Bean @Profile({ "dev", "qa" }) // 設置 dev test 環(huán)境開啟 public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(1000); performanceInterceptor.setFormat(true); return performanceInterceptor; } /** * 返回data1數(shù)據(jù)庫的數(shù)據(jù)源 * * @return */ @Bean(name = "primary") @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primary() { return DataSourceBuilder.create().build(); } @Bean(name = "secondary") // @Primary//主數(shù)據(jù)源 @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondary() { return DataSourceBuilder.create().build(); } @Bean("sqlSessionFactory") public SqlSessionFactory sqlSessionFactory() throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean(); sqlSessionFactory.setDataSource(multipleDataSource(primary(), secondary())); // sqlSessionFactory.setMapperLocations(new // PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*/*Mapper.xml")); MybatisConfiguration configuration = new MybatisConfiguration(); // configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class); configuration.setJdbcTypeForNull(JdbcType.NULL); configuration.setMapUnderscoreToCamelCase(true); configuration.setCacheEnabled(false); sqlSessionFactory.setConfiguration(configuration); sqlSessionFactory.setPlugins(new Interceptor[] { // PerformanceInterceptor(),OptimisticLockerInterceptor() paginationInterceptor() // 添加分頁功能 }); // sqlSessionFactory.setGlobalConfig(globalConfiguration()); return sqlSessionFactory.getObject(); } /** * 動態(tài)數(shù)據(jù)源配置 * * @return */ @Bean @Primary public DataSource multipleDataSource(@Qualifier("primary") DataSource db1, @Qualifier("secondary") DataSource db2) { MultipleDataSource multipleDataSource = new MultipleDataSource(); Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DataSourceEnum.DB1.getValue(), db1); targetDataSources.put(DataSourceEnum.DB2.getValue(), db2); // 添加數(shù)據(jù)源 multipleDataSource.setTargetDataSources(targetDataSources); // 設置默認數(shù)據(jù)源 multipleDataSource.setDefaultTargetDataSource(db1); return multipleDataSource; } }
二.配置其他
public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new InheritableThreadLocal<>(); /** * 設置數(shù)據(jù)源 * @param db */ public static void setDataSource(String db){ contextHolder.set(db); } /** * 取得當前數(shù)據(jù)源 * @return */ public static String getDataSource(){ return contextHolder.get(); } /** * 清除上下文數(shù)據(jù) */ public static void clear(){ contextHolder.remove(); } }
三.
public class MultipleDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { // TODO Auto-generated method stub return DataSourceContextHolder.getDataSource(); } }
測試是否成功
@RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("dev") public class SpringDataSourceApplicationTests { @Autowired private UserMapper userService; @Autowired private User02Service user02Service; @Test public void contextLoads() { User user = userService.selectById(1); User02 user02 = new User02(); BeanUtils.copyProperties(user, user02); user02Service.insert(user02); System.out.printf("數(shù)據(jù)是:"); } }
測試結果
到此這篇關于SpringBoot+MybatisPlus+jdbc連接池配置多數(shù)據(jù)源的實現(xiàn)的文章就介紹到這了,更多相關SpringBoot MybatisPlus jdbc多數(shù)據(jù)源內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java用三元運算符判斷奇數(shù)和偶數(shù)的簡單實現(xiàn)
這篇文章主要介紹了Java用三元運算符判斷奇數(shù)和偶數(shù)的簡單實現(xiàn),需要的朋友可以參考下2014-02-02java常用工具類之數(shù)據(jù)庫連接類(可以連接多種數(shù)據(jù)庫)
這篇文章主要介紹了java常用工具類之數(shù)據(jù)庫連接類,可以連接多種數(shù)據(jù)庫,代碼中包含詳細注釋,需要的朋友可以參考下2014-07-07SpringBoot使用WebJars統(tǒng)一管理靜態(tài)資源的方法
這篇文章主要介紹了SpringBoot使用WebJars統(tǒng)一管理靜態(tài)資源的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12用Java設計模式中的觀察者模式開發(fā)微信公眾號的例子
這篇文章主要介紹了用Java設計模式中的觀察者模式開發(fā)微信公眾號的例子,這里Java的微信SDK等部分便不再詳述,只注重關鍵部分和開發(fā)過程中觀察者模式優(yōu)點的體現(xiàn),需要的朋友可以參考下2016-02-02Java中使用Hutool的DsFactory操作多數(shù)據(jù)源的實現(xiàn)
在Java開發(fā)中,管理多個數(shù)據(jù)源是一項常見需求,Hutool作為一個全能的Java工具類庫,提供了DsFactory工具,幫助開發(fā)者便捷地操作多數(shù)據(jù)源,感興趣的可以了解一下2024-09-09