• SpringCloud ——@RefreshScope


    SpringCloud 配置中心帮助我们能动态地刷新应用的配置,只需要通过一个注解 @RefreshScope 即可。

    一直以为 @RefreshScope 会重新启动应用,直到同事遇到问题,一起调试后才发现,事实并非如此。

    验证过程非常简单,手写几个 ApplicationListener 即可。

    1. @Component
    2. public class CustomApplicationStartedListener implements ApplicationListener {
    3. @Override
    4. public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
    5. // @RefreshScope 修改配置文件后,并不触发该事件,换句话说没有重启应用
    6. ConfigurableApplicationContext applicationContext = applicationStartedEvent.getApplicationContext();
    7. System.out.println("首次启动:" + applicationContext);
    8. Object tjClient = applicationContext.getBean("tjClient");
    9. System.out.println("首次启动:" + tjClient);
    10. }

    1. @Component
    2. public class CustomContextRefreshedListener implements ApplicationListener {
    3. @Override
    4. public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    5. ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
    6. Object tjClient = applicationContext.getBean("tjClient");
    7. System.out.println(tjClient);
    8. }
    9. }

    应用启动后,刷新Nacos 上的配置文件,上面的两个 Listener 都没有走,只走了下面这个Listener

    1. @Component
    2. public class CustomRefreshScopeRefreshedListener implements ApplicationContextAware, ApplicationListener {
    3. private ApplicationContext applicationContext;
    4. @Override
    5. public void onApplicationEvent(RefreshScopeRefreshedEvent refreshScopeRefreshedEvent) {
    6. // @RefreshScope 刷新配置文件后,发出了 refreshScopeRefreshedEvent 事件, 而没有出发 ContextRefreshedEvent
    7. // 换句话说 applicationContext 仍然是同一个对象
    8. System.out.println("刷新Nacos配置文件后:" + applicationContext);
    9. // @RefreshScope 注解的对象,刷新后并没有立刻重新创建,而是在首次使用时,才创建,相当于懒加载
    10. Object tjClient = applicationContext.getBean("tjClient");
    11. System.out.println("刷新Nacos配置文件后:" + tjClient);
    12. }
    13. @Override
    14. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    15. this.applicationContext = applicationContext;
    16. }
    17. //RefreshScopeRefreshedEvent
    18. }

    打印结果也说明了 刷新配置文件时,applicationContext 并没有重建,应用没有重启!!

     

  • 相关阅读:
    selenium自动化测试过程中接口的调用信息
    27. 738.单调递增的数字,968.监控二叉树,贪心算法总结
    springboot2.0+vue 详细整合UEditor教程
    vue项目类微信聊天页面,输入法弹出,ios的标题会整体上移问题
    【上采样方式-OpenCV插值】
    webpack构建vue项目 基础03 之es6语法转化、js代码压缩
    纯后端如何写前端?我用了低代码平台
    React 组件的状态下移和内容提升
    Mybatis MappedStatement
    Linux安装配置awscli命令行接口工具及其从aws上传下载数据
  • 原文地址:https://blog.csdn.net/u011060911/article/details/125545347