iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring的@Value如何从Nacos配置中心获取值并自动刷新
  • 652
分享到

Spring的@Value如何从Nacos配置中心获取值并自动刷新

2024-04-02 19:04:59 652人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录@Value从Nacos配置中心获取值并自动刷新Nacos属性值自动刷新1.@NacosValue获取最新值2.@Value获取最新值@Value从Nacos配置中心获取值并自动

@Value从Nacos配置中心获取值并自动刷新

在使用Nacos作为配置中心时,除了@NacosValue可以做到自动刷新外,nacos-spring-context:0.3.4版本是支持@Value获取Nacos配置中心的值,并动态刷新的,该功能是Spri依靠ngValueAnnotationBeanPostProcessor类来实现:

@Override
    protected Tuple<String, NacosValueTarget> doWithAnnotation(String beanName,
            Object bean, Value annotation, int modifiers, Method method, Field field) {
        if (annotation != null) {
            if (Modifier.isStatic(modifiers)) {
                return Tuple.empty();
            }
 
            if (bean.getClass().isAnnotationPresent(NacosRefresh.class)) {
                String placeholder = resolvePlaceholder(annotation.value());
 
                if (placeholder == null) {
                    return Tuple.empty();
                }
 
                NacosValueTarget nacosValueTarget = new NacosValueTarget(bean, beanName,
                        method, field);
                nacosValueTarget.setAnnotationType(getAnnotationType().getSimpleName());
                logger.debug("@Value reGISter auto refresh");
                return Tuple.of(placeholder, nacosValueTarget);
            }
        }
        return Tuple.empty();
    }

分析其源码可以看到,如果bean上有注解@NacosRefresh,则会自动刷新。

在实际使用时,发现bean上的注解是@Configuration则不会自动刷新,而使用@Component则可以做到自动刷新。

代码如下:

@NacosRefresh
//@Component
@Configuration
public class BeanTest {
    
    @Value("${autofresh.test}")
    private String testValue;
    
    @NacosValue(value="${autofresh.test2}",autoRefreshed = true)
    private String testValue2;
 
    
    public String getTestValue2() {
        return testValue2;
    }
 
    
    public void setTestValue2(String testValue2) {
        this.testValue2 = testValue2;
    }
 
    
    public String getTestValue() {
        return testValue;
    }
 
    
    public void setTestValue(String testValue) {
        this.testValue = testValue;
    }
}

测试类:

@Test
     public void testValueRefreshinNacos() throws InterruptedException {
        System.out.println(beanTest.getTestValue());
        System.out.println(beanTest.getTestValue2()); 
        System.out.println("------修改前");
        
        Thread.sleep(1000*60);
        
        System.out.println(beanTest.getTestValue());
        System.out.println(beanTest.getTestValue2()); 
 
        System.out.println("------修改后");
     }

  

这就和@Component与@Configuration的区别有关了,@Component注解的bean是原生bean,@Configuration是被cglib动态增加的bean。

Nacos属性值自动刷新

1.@NacosValue获取最新值

引入jar包:  

          <dependency>
                 <groupId>com.alibaba.boot</groupId>
                 <artifactId>nacos-config-spring-boot-starter</artifactId>
                  <version>0.2.7</version>
            </dependency>

编写配置类:

       @Configuration
       @EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
       @NacosPropertySource(dataid = "example", group="test",autoRefreshed = true)
        public class NacosConfiguration { }

编写测试类:

       @Controller
       public class ConfiGController {
         @NacosValue(value = "${test.data}", autoRefreshed = true)
           private boolean data;                                     
          @RequestMapping(value = "/test", method = GET)
          @ResponseBody
          public boolean get() { return data; }
      }

2.@Value获取最新值

引入jar包:  

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>2.2.1.RELEASE</version>
</dependency>

引入配置:

spring:
  application:
    name: example
  cloud:
    nacos:
      config:
        extension-configs[0]:
          dataId: test.yml
          group: test
          refresh: true
        server-addr:  127.0.0.1:8848
        namespace: c845e96f-4423-4618-8c26-5e4d510f566a
        enabled: true
        refresh-enabled: true

编写测试类:

@RestController
@RefreshScope
public class TestController {
    @NacosValue(value = "${test.data}", autoRefreshed = true)
    private String data;
    @Value(value = "${test.data}")
    private String datas;
    @GetMapping("test")
    public String test() {
        return "data :" + data + ",datas="+datas;
    }
}

备注:

方式一@NacosValue获取最新值nacos配置信息需要写在配置类上

方式二@NacosValue获取不到值(如果需要使用该注解需要引入方式一的jar,但是不重启服务获取不到最新值),@Value获取最新值一定要加@RefreshScope注解,配置文件中配置refresh: true

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

--结束END--

本文标题: Spring的@Value如何从Nacos配置中心获取值并自动刷新

本文链接: https://www.lsjlt.com/news/153888.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作