好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

解决springboot环境切换失效的问题

springboot环境切换失效

概述

最近在使用-Dspring.profiles.active=te 来切换spring-boot的环境时,发现日志打印的是:

?

1

2

...ApplicationStartUp -

The following profiles are active: de

也就是说,参数失效了。

debug调试时,发现spring-boot读取的也是de,不是te。

解决

下载了一个新的tomcat,然后重新发布程序,设置参数,启动,发现环境正常切换了过来。

SpringBoot多数据源切换无效(不切换)

SpringBoot的多数据源实现以实现AbstractRoutingDataSource#determineCurrentLookupKey()来达到多个数据源动态切换的目的。

网上有很多的文章可以获取具体方法,就不在讲了。

项目中需要用到多数据源MySQL和SQLServer两个数据库,系统要保持两个数据库的数据同步,就需要来回切数据源来操作数据库。

刚写好了数据从MySQL同步到SQLServer中的代码,测试发现数据源不能切换到SQLServer数据库连接,排查问题~~省略n多个小时后,

源码解析等理论就不写了(重要的是不会写)直接上修改方案

CSDN查到的方案有

数据源切换和事务的注入顺序问题,像下面这样的,加入@Order注解。测试无效(可能我搭的架构有问题)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@Aspect

@Slf4j

@Order (- 1 ) // 保证优先级

@Component

public class DatasourceAspect {

     @Pointcut ( "@within(DataSource)|| @annotation(DataSource)" )

     public void pointcut() {

     }

     @Before ( "pointcut() && @annotation(dataSource)" )

     public void before(DataSource dataSource) {

         DatasourceContextHolder.setDatasource(dataSource.value().getDbName());

     }

     @After ( "pointcut()" )

     public void after() {

         DatasourceContextHolder.clear();

     }

}

Mapper(Dao)层切换数据源,反正我没找到怎么个用法,所以没有测试。 还有下面的这种写法。测试有效的

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@DataSource (DatasourceEnum.DB3)

    public int insertSelective( String hbNo, ) throws Exception{

        CcpHeaderSqlServer record = new CcpHeaderSqlServer();     

        if (log.isDebugEnabled()) {

            log.debug( "同步到SQLServer的数据对象:[{}]" , record);

        }   

     ......

    

     // 这种调用保存数据的方法,有效切换数据源

        XXXService service = SpringContextHolder.getBean(XXXService. class );

        return service.saveHeader(record);

    }

    @DataSource (DatasourceEnum.DB3)

    public int saveHeader(XXXEntity record) {

        return xxxMapper.insertSelective(record);

    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/limenghua9112/article/details/79608257

查看更多关于解决springboot环境切换失效的问题的详细内容...

  阅读:23次