溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

mysql 中怎么區(qū)分讀寫分離數(shù)據(jù)源

發(fā)布時間:2021-06-18 17:29:26 來源:億速云 閱讀:167 作者:Leah 欄目:大數(shù)據(jù)

mysql 中怎么區(qū)分讀寫分離數(shù)據(jù)源,針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

AOP中的@Aspect用法,用于監(jiān)控程序的執(zhí)行方法

Spring使用的AOP注解分為三個層次:

前提條件是在xml中放開了<aop:aspectj-autoproxy proxy-target-class="true"/><!-- 開啟切面編程功能 -->

1、@Aspect放在類頭上,把這個類作為一個切面。

2、 @Pointcut放在方法頭上,定義一個可被別的方法引用的切入點表達式。

3、5種通知。

3.1、@Before,前置通知,放在方法頭上。

3.2、@After,后置【finally】通知,放在方法頭上。

3.3、@AfterReturning,后置【try】通知,放在方法頭上,使用returning來引用方法返回值。

3.4、@AfterThrowing,后置【catch】通知,放在方法頭上,使用throwing來引用拋出的異常。

3.5、@Around,環(huán)繞通知,放在方法頭上,這個方法要決定真實的方法是否執(zhí)行,而且必須有返回值。

 
  1. @Component

  2. @Aspect

  3. public class LogAspect {

  4.  

  5. /**

  6. * 定義Pointcut,Pointcut的名稱 就是simplePointcut,此方法不能有返回值,該方法只是一個標示

  7. */

  8. @Pointcut("execution(public * com.service.impl..*.*(..))")

  9. public void recordLog() {

  10. }

  11.  

  12. @AfterReturning(pointcut = "recordLog()")

  13. public void simpleAdvice() {

  14. LogUtil.info("AOP后處理成功 ");

  15. }

  16.  

  17. @Around("recordLog()")

  18. public Object aroundLogCalls(ProceedingJoinPoint jp) throws Throwable {

  19. LogUtil.info("正常運行");

  20. return jp.proceed();

  21. }

  22.  

  23. @Before("recordLog()")

  24. public void before(JoinPoint jp) {

  25. String className = jp.getThis().toString();

  26. String methodName = jp.getSignature().getName(); // 獲得方法名

  27. LogUtil.info("位于:" + className + "調(diào)用" + methodName + "()方法-開始!");

  28. Object[] args = jp.getArgs(); // 獲得參數(shù)列表

  29. if (args.length <= 0) {

  30. LogUtil.info("====" + methodName + "方法沒有參數(shù)");

  31. } else {

  32. for (int i = 0; i < args.length; i++) {

  33. LogUtil.info("====參數(shù) " + (i + 1) + ":" + args[i]);

  34. }

  35. }

  36. LogUtil.info("=====================================");

  37. }

  38.  

  39. @AfterThrowing("recordLog()")

  40. public void catchInfo() {

  41. LogUtil.info("異常信息");

  42. }

  43.  

  44. @After("recordLog()")

  45. public void after(JoinPoint jp) {

  46. LogUtil.info("" + jp.getSignature().getName() + "()方法-結(jié)束!");

  47. LogUtil.info("=====================================");

  48. }

  49. }

細節(jié)介紹:

@AspectJ的詳細用法 
在spring AOP中目前只有執(zhí)行方法這一個連接點,Spring AOP支持的AspectJ切入點指示符如下:

一些常見的切入點的例子 
execution(public * * (. .)) 任意公共方法被執(zhí)行時,執(zhí)行切入點函數(shù)。 
execution( * set* (. .)) 任何以一個“set”開始的方法被執(zhí)行時,執(zhí)行切入點函數(shù)。 
execution( * com.demo.service.AccountService.* (. .)) 當接口AccountService 中的任意方法被執(zhí)行時,執(zhí)行切入點函數(shù)。 
execution( * com.demo.service.. (. .)) 當service 包中的任意方法被執(zhí)行時,執(zhí)行切入點函數(shù)。 within(com.demo.service.) 在service 包里的任意連接點。 within(com.demo.service. .) 在service 包或子包的任意連接點。 
this(com.demo.service.AccountService) 實現(xiàn)了AccountService 接口的代理對象的任意連接點。 
target(com.demo.service.AccountService) 實現(xiàn)了AccountService 接口的目標對象的任意連接點。 
args(Java.io.Serializable) 任何一個只接受一個參數(shù),且在運行時傳入?yún)?shù)實現(xiàn)了 Serializable 接口的連接點 
增強的方式: 
@Before:方法前執(zhí)行 
@AfterReturning:運行方法后執(zhí)行 
@AfterThrowing:Throw后執(zhí)行 
@After:無論方法以何種方式結(jié)束,都會執(zhí)行(類似于finally) 
@Around:環(huán)繞執(zhí)行

======================================mysql讀寫分離數(shù)據(jù)源配置================================

前文中 mysql3009是主庫 可以寫入操作 而mysql3008只能進行讀取操作

本文利用 AbstractRoutingDatasource實現(xiàn)業(yè)務(wù)代碼中動態(tài)的選擇讀取或?qū)懭氩僮鞯臄?shù)據(jù)源

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創(chuàng)建讀寫數(shù)據(jù)源
配置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配置的虛擬數(shù)據(jù)庫

用戶root有寫入權(quán)限  user為只讀權(quán)限 詳細參照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 用于獲取當前線程數(shù)據(jù)源并設(shè)置

@Component
public class DataSourceContextHolder {
    
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
 
    // 設(shè)置數(shù)據(jù)源類型
    public static void setDbType(String dbType) {
        contextHolder.set(dbType);
    }
 
    public static String getDbType() {
        return contextHolder.get();
    }
 
    public static void clearDbType() {
        contextHolder.remove();
    }
 
}
2將數(shù)據(jù)源注冊到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("當前數(shù)據(jù)源類型是:"+dbType);
        return dbType;
    }
    
    /**
     * 配置數(shù)據(jù)源信息
     */
    @Override
    public void afterPropertiesSet() {
        Map<Object, Object> map = new HashMap<>();
        map.put("selectDataSource", selectDataSource);
        map.put("updateDataSource", updateDataSource);
        setTargetDataSources(map);
        setDefaultTargetDataSource(updateDataSource);
        super.afterPropertiesSet();
    }
 
}
注意 注入讀寫數(shù)據(jù)源時要使用@qualifier注解 指定注入數(shù)據(jù)源 不然會報錯 同時類上要加上@primary 首選加載此類

3AOP攔截業(yè)務(wù)邏輯方法,通過方法名前綴判斷是讀還是寫操作
@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);
    }
}


 

關(guān)于mysql 中怎么區(qū)分讀寫分離數(shù)據(jù)源問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI