青柠檬檬哒|为什么要使用读写分离?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()方法得到的结果如下: