1 package com.fh.datademo.datasoucedynamic;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.beans.factory.annotation.Qualifier;
5 import org.springframework.context.annotation.Primary;
6 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
7 import org.springframework.stereotype.Component;
8
9
10 import javax.sql.DataSource;
11 import java.util.HashMap;
12 import java.util.Map;
13
14 /**
15 * @author yuchunqiang
16 * @Title: DynamicDataSource
17 * @Package com.fh.datademo.datasoucedynamic
18 * @Description: ${todo}
19 * @date 2018/10/24 16:06
20 */
21 @Component
22 @Primary
23 public class DynamicDataSource extends AbstractRoutingDataSource {
24
25 @Autowired
26 @Qualifier("selectDataSource")
27 private DataSource selectDataSource;
28
29 @Autowired
30 @Qualifier("updateDataSource")
31 private DataSource updateDataSource;
32
33 /**
34 * 這個是主要的方法,返回的是生效的數據源名稱
35 */
36 @Override
37 protected Object determineCurrentLookupKey() {
38 System.out.println("DataSourceContextHolder:::"+DataSourceContextHolder.getDbType());
39 return DataSourceContextHolder.getDbType();
40 }
41
42 /**
43 * 本身配的時候總是報什麼沒有指定target這裏設置一下,默認數據源是updateDataSource
44 */
45 @Override
46 public void afterPropertiesSet() {
47 Map<Object,Object> map = new HashMap<>();
48 map.put("selectDataSource",selectDataSource);
49 map.put("updateDataSource",updateDataSource);
50 setTargetDataSources(map);
51 setDefaultTargetDataSource(updateDataSource);
52 super.afterPropertiesSet();
53 }
54 }
1 package com.fh.datademo.datasoucedynamic;
2
3 import org.aspectj.lang.JoinPoint;
4 import org.aspectj.lang.annotation.Aspect;
5 import org.aspectj.lang.annotation.Before;
6 import org.springframework.context.annotation.Lazy;
7 import org.springframework.core.annotation.Order;
8 import org.springframework.stereotype.Component;
9
10 /**
11 * @author yuchunqiang
12 * @Title: SwitchDataSourceAOP
13 * @Package com.fh.datademo.datasoucedynamic
14 * @Description: ${todo}
15 * @date 2018/10/24 15:54
16 */
17 @Aspect
18 @Component
19 @Lazy(false)
20 @Order(0) //Order設定AOP執行順序 使之在數據庫事務上先執行
21 public class SwitchDataSourceAOP {
22
23 //這裏切到你的方法目錄
24 @Before("execution(* com.fh.datademo.service.*.*.*(..))")
25 public void process(JoinPoint joinPoint) {
26 String methodName=joinPoint.getSignature().getName();
27 if (methodName.startsWith("get")
28 ||methodName.startsWith("count")
29 ||methodName.startsWith("find")
30 ||methodName.startsWith("list")
31 ||methodName.startsWith("select")
32 ||methodName.startsWith("check")
33 ||methodName.startsWith("query")){
34 DataSourceContextHolder.setDbType("selectDataSource");
35 }else {
36 //切換dataSource
37 DataSourceContextHolder.setDbType("updateDataSource");
38 }
39 }
40
41 }