千家信息网

Spring多数据源AOP动态切换怎么实现

发表于:2025-01-20 作者:千家信息网编辑
千家信息网最后更新 2025年01月20日,这篇文章主要讲解了"Spring多数据源AOP动态切换怎么实现",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"Spring多数据源AOP动态切换怎么实现
千家信息网最后更新 2025年01月20日Spring多数据源AOP动态切换怎么实现

这篇文章主要讲解了"Spring多数据源AOP动态切换怎么实现",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"Spring多数据源AOP动态切换怎么实现"吧!

一:新增多数据源类

  1. public class DynamicDataSource extends AbstractRoutingDataSource {


  2. @Override

  3. protected Object determineCurrentLookupKey() {

  4. return DataSourceContextHolder.getDataSource();

  5. }


  6. }

点击(此处)折叠或打开

  1. public class DataSourceContextHolder {


  2. private static final ThreadLocal contextHolder = new ThreadLocal();


  3. public static void setDataSource(String dataSource) {

  4. contextHolder.set(dataSource);

  5. }


  6. public static String getDataSource() {

  7. return contextHolder.get();

  8. }


  9. }


二:新增注解

点击(此处)折叠或打开

  1. @Retention(RetentionPolicy.RUNTIME)

  2. @Target(ElementType.METHOD)

  3. @Documented

  4. public @interface DataSource {

  5. String value();

  6. }


三:新增AOP切面

点击(此处)折叠或打开

  1. @Aspect

  2. @Component

  3. public class DataSourceAspect {


  4. @Pointcut("@annotation(com.gemdale.ghome.business.async.deal.center.demo.datasource.DataSource)")

  5. public void dataSourcePointCut() {

  6. };


  7. @Before("dataSourcePointCut()")

  8. public void before(JoinPoint joinPoint) {


  9. System.out.println("=============dataSourcePointCut:before=============");


  10. Object target = joinPoint.getTarget();

  11. String method = joinPoint.getSignature().getName();


  12. // Class[] classz = target.getClass().getInterfaces();

  13. Class classz = target.getClass();

  14. Class[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getMethod().getParameterTypes();


  15. try {

  16. // Method m = classz[0].getMethod(method, parameterTypes);

  17. Method m = classz.getMethod(method, parameterTypes);

  18. if (null != m && m.isAnnotationPresent(DataSource.class)) {

  19. DataSource dataSource = m.getAnnotation(DataSource.class);

  20. DataSourceContextHolder.setDataSource(dataSource.value());


  21. System.out.println("=============dataSource:" + dataSource.value());

  22. }

  23. }

  24. catch (Exception e) {

  25. e.printStackTrace();

  26. }

  27. }


  28. }


四:数据源配置

点击(此处)折叠或打开

  1. @Configuration

  2. public class DynamicTransactionManagerElConfig {


  3. @Autowired

  4. @Qualifier("platformTomcat")

  5. private DataSource platformTomcat;


  6. @Autowired

  7. @Qualifier("platformReadTomcat")

  8. private DataSource platformReadTomcat;


  9. @Bean(name = "dataSource")

  10. public DynamicDataSource dataSource() {

  11. DynamicDataSource dataSource = new DynamicDataSource();

  12. Map targetDataSources = new HashMap<>();

  13. targetDataSources.put("master", platformTomcat);

  14. targetDataSources.put("slave", platformReadTomcat);

  15. dataSource.setTargetDataSources(targetDataSources);

  16. dataSource.setDefaultTargetDataSource(platformTomcat);

  17. return dataSource;

  18. }



  19. @Bean(name = "jdbcTemplate")

  20. public JdbcTemplate jdbcTemplate(DynamicDataSource dataSource) {

  21. JdbcTemplate jdbcTemplate = new JdbcTemplate();

  22. jdbcTemplate.setDataSource(dataSource);

  23. return jdbcTemplate;

  24. }


  25. @Bean(name = "jdbcReadTemplate")

  26. public JdbcTemplate jdbcReadTemplate(DynamicDataSource dataSource) {

  27. JdbcTemplate jdbcReadTemplate = new JdbcTemplate();

  28. jdbcReadTemplate.setDataSource(dataSource);

  29. return jdbcReadTemplate;

  30. }



  31. @Bean(name = "transactionManager")

  32. public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) {

  33. DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();

  34. transactionManager.setDataSource(dataSource);

  35. return transactionManager;

  36. }


  37. }


五:应用举例

点击(此处)折叠或打开

  1. @Service("gmcSmsInfoBo")

  2. public class GmcSmsInfoBo extends AbstractBusinessObject {


  3. @Autowired

  4. private GmcSmsInfoDAO gmcSmsInfoDaoImpl;


  5. // @CachePut(value = "GmcSmsInfoCache", key = "'GmcSmsInfo_'+#result.smsId")

  6. // @Transactional(rollbackFor={Exception.class,RuntimeException.class})

  7. @DataSource("master")

  8. public GmcSmsInfo add(GmcSmsInfo smsInfo) throws BusinessServiceException {

  9. System.out.println("=============add==========");

  10. try {

  11. smsInfo.setSmsId(gmcSmsInfoDaoImpl.save(smsInfo));

  12. }

  13. catch (FrameworkDAOException e) {

  14. throw new BusinessServiceException(e);

  15. }

  16. return smsInfo;

  17. }


  18. // @Cacheable(value="GmcSmsInfoCache",key="'GmcSmsInfo_'+#smsId")

  19. @DataSource("slave")

  20. public GmcSmsInfo query(Integer smsId) throws BusinessServiceException {

  21. System.out.println("=============query==========");

  22. try {

  23. return gmcSmsInfoDaoImpl.findById(GmcSmsInfo.class, smsId);

  24. }

  25. catch (Exception e) {

  26. throw new BusinessServiceException(e);

  27. }

  28. }


  29. }

感谢各位的阅读,以上就是"Spring多数据源AOP动态切换怎么实现"的内容了,经过本文的学习后,相信大家对Spring多数据源AOP动态切换怎么实现这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

0