參考博客:java
https://blog.csdn.net/bsmmaoshenbo/article/details/60766300mysql
https://blog.csdn.net/baiyan3212/article/details/90901471web
============================AOP中的@Aspect用法,用於監控程序的執行方法=========================spring
Spring使用的AOP註解分爲三個層次:sql
前提條件是在xml中放開了<aop:aspectj-autoproxy proxy-target-class="true"/><!-- 開啓切面編程功能 -->數據庫
一、@Aspect放在類頭上,把這個類做爲一個切面。編程
二、 @Pointcut放在方法頭上,定義一個可被別的方法引用的切入點表達式。mybatis
三、5種通知。app
3.一、@Before,前置通知,放在方法頭上。maven
3.二、@After,後置【finally】通知,放在方法頭上。
3.三、@AfterReturning,後置【try】通知,放在方法頭上,使用returning來引用方法返回值。
3.四、@AfterThrowing,後置【catch】通知,放在方法頭上,使用throwing來引用拋出的異常。
3.五、@Around,環繞通知,放在方法頭上,這個方法要決定真實的方法是否執行,並且必須有返回值。
@Component
@Aspect
public class LogAspect {
/**
* 定義Pointcut,Pointcut的名稱 就是simplePointcut,此方法不能有返回值,該方法只是一個標示
*/
@Pointcut("execution(public * com.service.impl..*.*(..))")
public void recordLog() {
}
@AfterReturning(pointcut = "recordLog()")
public void simpleAdvice() {
LogUtil.info("AOP後處理成功 ");
}
@Around("recordLog()")
public Object aroundLogCalls(ProceedingJoinPoint jp) throws Throwable {
LogUtil.info("正常運行");
return jp.proceed();
}
@Before("recordLog()")
public void before(JoinPoint jp) {
String className = jp.getThis().toString();
String methodName = jp.getSignature().getName(); // 得到方法名
LogUtil.info("位於:" + className + "調用" + methodName + "()方法-開始!");
Object[] args = jp.getArgs(); // 得到參數列表
if (args.length <= 0) {
LogUtil.info("====" + methodName + "方法沒有參數");
} else {
for (int i = 0; i < args.length; i++) {
LogUtil.info("====參數 " + (i + 1) + ":" + args[i]);
}
}
LogUtil.info("=====================================");
}
@AfterThrowing("recordLog()")
public void catchInfo() {
LogUtil.info("異常信息");
}
@After("recordLog()")
public void after(JoinPoint jp) {
LogUtil.info("" + jp.getSignature().getName() + "()方法-結束!");
LogUtil.info("=====================================");
}
}
細節介紹:
@AspectJ的詳細用法
在spring AOP中目前只有執行方法這一個鏈接點,Spring AOP支持的AspectJ切入點指示符以下:
一些常見的切入點的例子
execution(public * * (. .)) 任意公共方法被執行時,執行切入點函數。
execution( * set* (. .)) 任何以一個「set」開始的方法被執行時,執行切入點函數。
execution( * com.demo.service.AccountService.* (. .)) 當接口AccountService 中的任意方法被執行時,執行切入點函數。
execution( * com.demo.service.. (. .)) 當service 包中的任意方法被執行時,執行切入點函數。 within(com.demo.service.) 在service 包裏的任意鏈接點。 within(com.demo.service. .) 在service 包或子包的任意鏈接點。
this(com.demo.service.AccountService) 實現了AccountService 接口的代理對象的任意鏈接點。
target(com.demo.service.AccountService) 實現了AccountService 接口的目標對象的任意鏈接點。
args(Java.io.Serializable) 任何一個只接受一個參數,且在運行時傳入參數實現了 Serializable 接口的鏈接點
加強的方式:
@Before:方法前執行
@AfterReturning:運行方法後執行
@AfterThrowing:Throw後執行
@After:不管方法以何種方式結束,都會執行(相似於finally)
@Around:環繞執行
=============================mysql 數據源配置==========================================
前文中 mysql3009是主庫 能夠寫入操做 而mysql3008只能進行讀取操做
本文利用 AbstractRoutingDatasource實現業務代碼中動態的選擇讀取或寫入操做的數據源
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.23</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
1建立讀寫數據源
配置application.yml
spring:
datasource:
update:
jdbc-url: jdbc:mysql://192.168.43.66:8066/mycat_testdb
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
select:
jdbc-url: jdbc:mysql://192.168.43.66:8066/mycat_testdb
driver-class-name: com.mysql.jdbc.Driver
username: user
password: user
type: com.alibaba.druid.pool.DruidDataSource
其中 jdbc-url爲mycat配置的虛擬數據庫
用戶root有寫入權限 user爲只讀權限 詳細參照mycat的server.xml文件配置
DatasourceConfig
@Configuration
public class DatasourceConfig {
@Bean
@ConfigurationProperties(prefix="spring.datasource.select")
public DataSource selectDataSource(){
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix="spring.datasource.update")
public DataSource updateDataSource(){
return DataSourceBuilder.create().build();
}
}
DataSourceContextHolder 用於獲取當前線程數據源並設置
@Component
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
// 設置數據源類型
public static void setDbType(String dbType) {
contextHolder.set(dbType);
}
public static String getDbType() {
return contextHolder.get();
}
public static void clearDbType() {
contextHolder.remove();
}
}
2將數據源註冊到AbstractRoutingDataSource
@Primary
@Component
public class DynamicDatasource extends AbstractRoutingDataSource{
@Autowired
@Qualifier("selectDataSource")
private DataSource selectDataSource;
@Autowired
@Qualifier("updateDataSource")
private DataSource updateDataSource;
@Override
protected Object determineCurrentLookupKey() {
String dbType = DataSourceContextHolder.getDbType();
System.out.println("當前數據源類型是:"+dbType);
return dbType;
}
/**
* 配置數據源信息
*/
@Override
public void afterPropertiesSet() {
Map<Object, Object> map = new HashMap<>();
map.put("selectDataSource", selectDataSource);
map.put("updateDataSource", updateDataSource);
setTargetDataSources(map);
setDefaultTargetDataSource(updateDataSource);
super.afterPropertiesSet();
}
}
注意 注入讀寫數據源時要使用@qualifier註解 指定注入數據源 否則會報錯 同時類上要加上@primary 首選加載此類
3AOP攔截業務邏輯方法,經過方法名前綴判斷是讀仍是寫操做
@Aspect
@Component
public class DataSourceAop {
@Pointcut("execution(* com.xuxu.service.*.*(..))")
public void cutPoint(){
}
@Before("cutPoint()")
public void process(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
if (methodName.startsWith("get") || methodName.startsWith("count") || methodName.startsWith("find")
|| methodName.startsWith("list") || methodName.startsWith("select") || methodName.startsWith("check")) {
DataSourceContextHolder.setDbType("selectDataSource");
} else {
// 切換dataSource
DataSourceContextHolder.setDbType("updateDataSource");
}
}
}
測試
mapper
@Mapper
public interface UserMapper {
@Insert("insert into test (id) values(#{id})")
public int insert(@Param("id") Integer id);
@Select("select * from test")
public List<Integer> getAll();
@Update("update test set id=#{id} where id=#{targetId}")
public int update(@Param("targetId") Integer targetId,@Param("id") Integer id);
}
service
@Service
public class TestDatasourceService {
@Autowired
private UserMapper userMapper;
public int insert(Integer id){
return userMapper.insert(id);
}
public List<Integer> getAll(){
return userMapper.getAll();
}
public int update(Integer targetId,Integer id){
return userMapper.update(targetId, id);
}
}
controller
@RestController
public class TestDatasourceController {
@Autowired
private TestDatasourceService testService;
@RequestMapping("/insert/{id}")
public int insert(@PathVariable Integer id){
return testService.insert(id);
}
@RequestMapping("/get")
public List<Integer> getAll(){
return testService.getAll();
}
@RequestMapping("/update")
public int update(Integer targetId,Integer id){
return testService.update(targetId, id);
}
}
實現動態數據源 ————————————————