@Qualifier(“jdbcTemplate2”)
JdbcTemplate jdbcTemplate;
这种方式当然可以实现,但是呢不够优雅,下面我们讲下如何使用更加优雅的实现方式。重点:AbstractRoutingDataSource
2. 准备动态数据源
AbstractRoutingDataSource
是什么?
这个可以直接查看源码,里面注释如下:
Abstract {@link javax.sql.DataSource} implementation that routes {@link #getConnection()}
calls to one of various target DataSources based on a lookup key. The latter is usually
(but not necessarily) determined through some thread-bound transaction context.
白话翻译一下:通过线程绑定的事务上下文动态确定数据源
核心属性、方法如下:
// 保存了key和数据源的映射
private Map<Object, Object> targetDataSources;
// 默认数据源
private Object defaultTargetDataSource;
// 抽像方法,需要重写然后在protected DataSource determineTargetDataSource() 中调用
// 用来确定使用哪个数据源,核心
protected abstract Object determineCurrentLookupKey();
那么我们创建建一个作为默认的datasource
继承自AbstractRoutingDataSource
,并且覆盖determineCurrentLookupKey()
方法,来以实现数据库的动态切换
@Slf4j
public class ThreadLocalRountingDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal ThreadLocalDataSourceKey = new ThreadLocal();
public static void clear() {
log.info(“清除当前线程数据源”);
ThreadLocalDataSourceKey.remove();
}
@Override
protected Object determineCurrentLookupKey() {
String dataSourceKey = ThreadLocalDataSourceKey.get();
log.info(“通过key确定当前应该使用哪个数据源, key:{}”, dataSourceKey);
return dataSourceKey;
}
public static void setDataSourceKey(String dataSourceKey) {
log.info(“设置需要使用的数据源key, key:{}”, dataSourceKey);
ThreadLocalDataSourceKey.set(dataSourceKey);
}
}
把动态路由数据源设置主数据源,并给配置不同的数据源
@Bean
@Primary
public ThreadLocalRountingDataSource threadLocalRountingDataSource() {
ThreadLocalRountingDataSource dataSource = new ThreadLocalRountingDataSource();
Map<Object, Object> targetDataSources = new HashMap();
DataSource master = dataSource1();//默认数据源
DataSource other = dataSource2();//其他数据源
targetDataSources.put(“master”, master);
targetDataSources.put(“other”, other);
// 设置数据源池的key和数据源的映射
dataSource.setTargetDataSources(targetDataSources);
// 把主数据源设置为默认数据源
dataSource.setDefaultTargetDataSource(master);
return dataSource;
}
3. 自定义注解+aop实现
自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LakerDataSource {
String value() default “master”;
}
定义拦截器
@Aspect
@Order(Ordered.LOWEST_PRECEDENCE - 1)
@Component
public class LakerDataSourceAspect {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut(“@annotation(com.laker.notes.multidatasource.LakerDataSource)”)
public void lakerDataSource() {
}
@Around(“lakerDataSource()”)
public Object around(ProceedingJoinPoint point) throws Throwable {
LakerDataSource dataSource = getDataSource(point);
//设置数据源
if (dataSource != null) {
ThreadLocalRountingDataSource.setDataSourceKey(dataSource.value());
}
try {
return point.proceed();
} catch (Exception e) {
throw e;
} finally {
// 销毁数据源 在执行方法之后
ThreadLocalRountingDataSource.clear();
}
}
/**
- 获取需要切换的数据源
*/
public LakerDataSource getDataSource(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
LakerDataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), LakerDataSource.class);
if (Objects.nonNull(dataSource)) {
return dataSource;
}
return AnnotationUtils.findAnnotation(signature.getDeclaringType(), LakerDataSource.class);
}
}
重点: 该切面必须要在事务注解@Transactional之前,由于在开始事务之前就需要确定数据源,所以设置DataSourceAsp的
@Order(Ordered.LOWEST_PRECEDENCE-1)
,@Transactional的order是最小值
4. 验证
sevice
@Service
public class UserService {
@Autowired
private UserDao userDao;
@LakerDataSource(“master”)
public LakerUser getDataSourceMaster(Long id) {
return userDao.findById(id).get();
}
@LakerDataSource(“other”)
public LakerUser getDataSourceOther(Long id) {
return userDao.findById(id).get();
}
}
controller
@RestController
@Slf4j
public class DataSourceController {
@Autowired
private UserService userService;
@GetMapping(“/master”)
public LakerUser master(Long id) throws Exception {
LakerUser lakerUser = userService.getDataSourceMaster(id);
log.info(lakerUser.toString());
return lakerUser;
}
@GetMapping(“/other”)
public LakerUser other(Long id) throws Exception {
LakerUser lakerUser = userService.getDataSourceOther(id);
log.info(lakerUser.toString());
return lakerUser;
}
}
浏览器输入:http://localhost:8080/master?id=1
[nio-8080-exec-1] c.l.n.m.ThreadLocalRountingDataSource : 设置需要使用的数据源key, key:master
[nio-8080-exec-1] c.l.n.m.ThreadLocalRountingDataSource : 通过key确定当前应该使用哪个数据源, key:master
[nio-8080-exec-1] c.l.n.m.ThreadLocalRountingDataSource : 清除当前线程数据源
[nio-8080-exec-1] c.l.n.m.DataSourceController : LakerUser(id=1, name=laker, age=30)
浏览器输入:http://localhost:8080/other?id=1
[nio-8080-exec-2] c.l.n.m.ThreadLocalRountingDataSource : 设置需要使用的数据源key, key:other
[nio-8080-exec-2] c.l.n.m.ThreadLocalRountingDataSource : 通过key确定当前应该使用哪个数据源, key:other
[nio-8080-exec-2] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Starting…
[nio-8080-exec-2] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Start completed.
[nio-8080-exec-2] c.l.n.m.ThreadLocalRountingDataSource : 清除当前线程数据源
[nio-8080-exec-2] c.l.n.m.DataSourceController : LakerUser(id=1, name=laker100, age=100)
从日志中可以看到,已经实现了动态数据源的切换功能。