温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

mysql 中怎么区分读写分离数据源

发布时间:2021-06-18 17:29:26 来源:亿速云 阅读:164 作者:Leah 栏目:大数据

mysql 中怎么区分读写分离数据源,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

AOP中的@Aspect用法,用于监控程序的执行方法

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,环绕通知,放在方法头上,这个方法要决定真实的方法是否执行,而且必须有返回值。

 
  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 + "调用" + methodName + "()方法-开始!");

  28. Object[] args = jp.getArgs(); // 获得参数列表

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

  30. LogUtil.info("====" + methodName + "方法没有参数");

  31. } else {

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

  33. LogUtil.info("====参数 " + (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() + "()方法-结束!");

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

  48. }

  49. }

细节介绍:

@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);
    }
}


 

关于mysql 中怎么区分读写分离数据源问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI