青柠檬檬哒|为什么要使用读写分离?SpirngBoot+MyBatis如何实现读写分离?( 二 )
publicenumDBTypeEnum{MASTER,SLAVE}//线程级别的数据源设置publicclassDBContextHolder{privatestaticfinalThreadLocalcontextHolder=newThreadLocal<>();publicstaticvoidset(DBTypeEnumdbType){contextHolder.set(dbType);}publicstaticDBTypeEnumget(){returncontextHolder.get();}publicstaticvoidmaster(){set(DBTypeEnum.MASTER);System.out.println("切换到master");}publicstaticvoidslave(){set(DBTypeEnum.SLAVE);System.out.println("切换到slave");}}//定义AOP规则进行数据源的动态切换@Component@AspectpublicclassDataSourceAop{@Pointcut("@annotation(com.kxg.demo.annotation.ReadOnly)"+"||execution(*com.kxg.demo.mapper..*.find*(..))"+"||execution(*com.kxg.demo.mapper..*.get*(..))")publicvoidreadPointcut(){}@Pointcut("!@annotation(com.kxg.demo.annotation.ReadOnly)"+"&&execution(*com.kxg.demo.mapper..*.insert*(..))"+"||execution(*com.kxg.demo.mapper..*.update*(..))"+"||execution(*com.kxg.demo.mapper..*.delete*(..))")publicvoidwritePointcut(){}@Before("readPointcut()")publicvoidread(){DBContextHolder.slave();}@Before("writePointcut()")publicvoidwrite(){DBContextHolder.master();}}5、测试结果
@DatapublicclassUser{privateIntegeruserId;privateStringuserName;}insertintotb_user(user_id,user_name)values(#{userId},#{userName})@MapperpublicinterfaceUserMapper{ListfindAll();intinsert(Useruser);}@ServicepublicclassUserService{@AutowiredprivateUserMapperuserMapper;@Transactionalpublicvoidinsert(Useruser){userMapper.insert(user);}@Transactionalpublicvoidsave(){}//打上readOnly的注解 , 表示走读库@ReadOnlypublicListfindAll(){returnuserMapper.findAll();}}//写个测试方法测试一下@RunWith(SpringRunner.class)@SpringBootTest(classes=MultiDataSourceDemo.class)@MapperScan(basePackages="com.kxg.demo")@SpringBootApplication(exclude=DataSourceAutoConfiguration.class)publicclassMultiDataSourceDemo{@AutowiredprivateUserServiceuserService;@TestpublicvoidtestWrite(){Useruser=newUser();IntegeruserId=newRandom().nextInt();user.setUserId(userId);user.setUserName("user"+userId);userService.insert(user);}@TestpublicvoidtestRead(){userService.findAll();}}分别运行testWrite()、testRead()方法得到的结果如下:
- 帅气的烨烨|为什么600年来无人敢盗, 连孙殿英都怕?,明孝陵至今保存完好,
- 毒蛇|“冰火蛇”是什么来头?为什么它会被认为是地球上毒性最强的蛇?
- 腾讯微博|既然网盘生意那么烧钱,为什么阿里迅雷还要和百度网盘抢饭碗?
- 白宫|火星有生命吗?为什么探测器拍到形似“发动机”、“士兵”等物体
- 道达网络货运平台|为什么连互联网巨头都想加入网络货运?
- 移动支付|为什么全国加油站将停用微信支付?这其中有什么用意呢?
- 帝释天|为什么世界各地的神话竟然惊人地相似?也许宙斯跟帝释天是同一人
- 青柠檬檬哒|无线电二厂虎啸,可做蓝牙音箱的功能机
- 点点雨落山岚|马化腾也表示无奈:为什么你们都将QQ号卖了?原来能换套房子
- 行星|牛奶是必需品还是阴谋?为什么人类是成年以后唯一能喝奶的动物?