SpringBoot配置多数据源(注解⽅式)
看了有些多数据源的整合⽂章,感觉有点乱,所以⾃⼰记录⼀下以后总会⽤得到。
别问问什么投原创,我的⼏个例⼦页⾯不到了真的
鞠躬了!
SpringBoot多数据源配置(注解⽅式)
Maven依赖
<dependency>
<groupId&batis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
yml⽂件配置
spring:
datasource:
db1:#实操以及展⽰
driver-class-name-: sql.jdbc.Driver
jdbc-url: jdbc:mysql://192.168.1.11:3306/js1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKe yRetrieval=true
username: root
password: w123!!
db2:#机考
driver-class-name: com.ibm.db2.jcc.DB2Driver
jdbc-url: jdbc:db2://192.168.1.134:50000/w
username: db2admin
password:"db2admin"
设置数据源常量
这部分是借鉴的(抄的)
public class DataSourceConstants {
public final static String MASTER ="db1";
public final static String SLAVE ="db2";
}
功能快捷键
这部分是也借鉴的(也是抄的)
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey(){
ContextKey();
}
}
class DynamicDataSourceContextHolder {
spring ioc注解
/* 动态数据源名称上下⽂*/
private static final ThreadLocal<String> DATASOURCE_CONTEXT_KEY_HOLDER =new ThreadLocal<>();
/* 设置/切换数据源*/
public static void setContextKey(String key){
System.out.println("切换数据源"+key);
DATASOURCE_CONTEXT_KEY_HOLDER.set(key);
}
/* 获取数据源名称 */
public static String getContextKey(){
String key = DATASOURCE_CONTEXT_();
return key == null ? DataSourceConstants.MASTER : key;
}
/*删除当前数据源名称*/
public static void removeContextKey(){
DATASOURCE_CONTEXT_ve();
}
}
⾃定义注解
@Target({ElementType.METHOD,ElementType.TYPE}) 可应⽤于⽅法、类、接⼝
import com.windmill.datasource.DataSourceConstants;
import java.lang.annotation.*;
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {
//默认主数据源
String value()default DataSourceConstants.MASTER;
}
增加配置
@Configuration 定义配置类
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) ⾃定义数据源,不使⽤SpringBoot默认配置@Primary 默认优先选择
@ConfigurationProperties 设置默认的属性值
@Bean 将实例注⼊到Spring IOC
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.t.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder;
import t.annotation.Bean;
import t.annotation.Configuration;
import t.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableAutoConfiguration(exclude ={ DataSourceAutoConfiguration.class}) public class DynamicDataSourceConfig {
@Bean(DataSourceConstants.MASTER)
@ConfigurationProperties(prefix ="spring.datasource.db1")
public DataSource masterDataSource(){
ate().build();
}
@Bean(DataSourceConstants.SLAVE)
@ConfigurationProperties(prefix ="spring.datasource.db2")
public DataSource slaveDataSource(){
ate().build();
}
@Bean
@Primary
public DataSource dynamicDataSource(){
Map<Object, Object> dataSourceMap =new HashMap<>(2);
dataSourceMap.put(DataSourceConstants.MASTER,masterDataSource());        dataSourceMap.put(DataSourceConstants.SLAVE,slaveDataSource());
//设置动态数据源
DynamicDataSource dynamicDataSource =new DynamicDataSource();
dynamicDataSource.setTargetDataSources(dataSourceMap);
dynamicDataSource.setDefaultTargetDataSource(masterDataSource());
return dynamicDataSource;
}
}
增加切⾯,拦截注解
不解释了 :-)
import com.windmill.annotations.DataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.flect.MethodSignature;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Aspect
@Component
public class DynamicDataSourceAspect {
//拦截注解⽅法
@Pointcut("@annotation(com.windmill.annotations.DataSource)")
public void dataSourcePointCut(){
}
@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint joinPoint)throws Throwable {
String dsKey =DSAnnotation(joinPoint).value();
DynamicDataSourceContextHolder.setContextKey(dsKey);
try{
return joinPoint.proceed();
}catch(Exception ex){
throw ex;
}finally{
}
}
/**
* 根据类或⽅法获取数据源注解
*/
private DataSource getDSAnnotation(ProceedingJoinPoint joinPoint){
//mybatis⽣成的代理类,所以获取它的接⼝来获取DbAnnotation注解信息
Class<?> targetClass = Target().getClass().getInterfaces()[0];
DataSource dsAnnotation = Annotation(DataSource.class);
/
/ 先判断类的注解,再判断⽅法注解
Null(dsAnnotation)){
return dsAnnotation;
}else{
MethodSignature methodSignature =(MethodSignature) Signature();
DataSource annotation = Method().getAnnotation(DataSource.class);
return annotation;
}
}
}
使⽤⽅法
@Mapper
public interface BaseInfoMapper {
@DataSource(DataSourceConstants.SLAVE)
List<Baseinfo>selectUserList(@Param("orgId") orgId);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。