草庐IT

Spring 中使用Nacos配置管理

没事儿写两篇 2023-04-11 原文

添加依赖

<dependency>
    <groupId>com.alibaba.nacos</groupId>
    <artifactId>nacos-spring-context</artifactId>
    <version>${latest.version}</version>
</dependency>

本文使用的版本为:1.1.1

注:我们在Nacos使用SDK的时候引入了nacos-client依赖,nacos-spring-context默认有nacos-client的依赖,本文示例请勿自己添加Nacos-client依赖,否则后续的示例会有意想不到的错误。

  • 我们Nacos的Java SDK一文中引用的nacos-client版本为2.2.0,nacos-spring-context 1.1.1版本依赖的nacos-client版本为1.4.1所以会有版本差异,会出现方法不存在等错误问题。

Spring使用Nacos的配置模块

package com.yyoo.nacos.spring;

import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
@NacosPropertySource(dataId = "com.yyoo.nacos.sdk.CofingServiceTest",groupId = "Nacos:Test"
        ,autoRefreshed = true,type = ConfigType.JSON)
public class NacosConfiguration {

}
  • @EnableNacosConfig 注解启用 Nacos Spring 的配置管理服务
  • globalProperties全局配置,是使用@NacosProperties注解加载的全局配置
  • @NacosProperties 是全局和自定义 Nacos 属性的统一注解。 它充当Java Properties 和 NacosFactory 类之间的中介。
  • @NacosPropertySource其作用与Spring的@PropertySource作用一样,是读取配置到Spring容器中
  • dataId我们在Nacos中的配置id,groupId我们在Nacos中的groupId。
  • autoRefreshed 为true表示,如果配置修改容器将自动更新配置
  • type即我们的配置的类型,这里是Json类型

Nacos中发布的示例配置

获取配置的示例

package com.yyoo.nacos.spring;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.stereotype.Controller;

@Controller
public class NacosTestController {

    @NacosValue(value = "${conf1:default}", autoRefreshed = true)
    private String conf1;

    public String getConf1() {
        return conf1;
    }
}

我们模拟了一个Controller,获取Nacos中的conf1配置。

  • @NacosValue 的作用相当于Spring中的@Value
package com.yyoo.nacos.spring.test;

import com.yyoo.nacos.spring.NacosTestController;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class NacosTest {

    @Test
    public void testSpring(){

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.scan("com.yyoo");
        context.refresh();

        NacosTestController controller = context.getBean(NacosTestController.class);
        System.out.println(controller.getConf1());

    }

}

示例代码执行之后,会输出结果:test1

  • 注:本示例需要使用Spring的相关依赖和知识。

示例二

package com.yyoo.nacos.spring.bean;

import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties;
import com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
@NacosConfigurationProperties(dataId = "com.yyoo.nacos.sdk.CofingServiceTest",groupId = "Nacos:Test"
        ,autoRefreshed = true,prefix = "my",type = ConfigType.JSON)
public class MyPro {
    private String conf1;

    private String conf2;

    public String getConf1() {
        return conf1;
    }

    public void setConf1(String conf1) {
        this.conf1 = conf1;
    }

    public String getConf2() {
        return conf2;
    }

    public void setConf2(String conf2) {
        this.conf2 = conf2;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("MyPro{");
        sb.append("conf1='").append(conf1).append('\'');
        sb.append(", conf2='").append(conf2).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

Nacos界面修改配置

    @Test
    public void testSpring2(){

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.scan("com.yyoo");
        context.refresh();

        MyPro pro = context.getBean(MyPro.class);
        System.out.println(pro);

    }

输出结果:MyPro{conf1=‘test1’, conf2=‘test3’}

Nacos配置注解与Spring的配置注解的对应

SpringNacos说明
@Value@NacosValue
@ConfigurationProperties@NacosConfigurationProperties对应字段上可以使用@NacosProperty,@NacosIgnore
@PropertySource@NacosPropertySource
@PropertySources@NacosPropertySources

Nacos的这些注解的主要作用与Spring对应的注解一样

Nacos配置注解说明

全局 Nacos 属性

globalProperties 将初始化为其他注解或组件的 “全局 Nacos 属性”

globalProperties 是任何 @EnableNacos,@EnableNacosDiscovery 或 @EnableNacosConfig 中的必选属性,其类型为 @NacosProperties。示例:@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = “127.0.0.1:8848”))

全局 Nacos 属性 定义全局和默认属性。它设置为具有最低优先级,并且也可以被覆盖。覆盖优先级如下:

优先级配置说明
1*.properties()最高优先级
2@EnableNacosConfig.globalProperties() 或 @EnableNacosDiscovery.globalProperties()
3@EnableNacos.globalProperties()最低优先级

*.properties() 定义来自以下之一的自定义 Nacos 属性:

  • @NacosInjected.properties()
  • @NacosConfigListener.properties()
  • @NacosPropertySource.properties()
  • @NacosConfigurationProperties.properties()

自定义的 Nacos 属性也由 @NacosProperties 配置。 不过,它们是可选的,用于在特殊情况下覆盖全局 Nacos 属性。 如果没有定义,Nacos 属性将尝试从 @EnableNacosConfig.globalProperties() 或 @EnableNacosDiscovery.globalProperties() 或 @EnableNacos.globalProperties() 中查找属性。

配置注解的占位符

占位符直接查看源码就行了,比如查看@NacosProperties的源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.alibaba.nacos.api.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NacosProperties {
    String PREFIX = "nacos.";
    String ENDPOINT = "endpoint";
    String NAMESPACE = "namespace";
    String ACCESS_KEY = "access-key";
    String SECRET_KEY = "secret-key";
    String SERVER_ADDR = "server-addr";
    String CONTEXT_PATH = "context-path";
    String CLUSTER_NAME = "cluster-name";
    String ENCODE = "encode";
    String CONFIG_LONG_POLL_TIMEOUT = "configLongPollTimeout";
    String CONFIG_RETRY_TIME = "configRetryTime";
    String MAX_RETRY = "maxRetry";
    String ENABLE_REMOTE_SYNC_CONFIG = "enableRemoteSyncConfig";
    String USERNAME = "username";
    String PASSWORD = "password";
    String ENDPOINT_PLACEHOLDER = "${nacos.endpoint:}";
    String NAMESPACE_PLACEHOLDER = "${nacos.namespace:}";
    String ACCESS_KEY_PLACEHOLDER = "${nacos.access-key:}";
    String SECRET_KEY_PLACEHOLDER = "${nacos.secret-key:}";
    String SERVER_ADDR_PLACEHOLDER = "${nacos.server-addr:}";
    String CONTEXT_PATH_PLACEHOLDER = "${nacos.context-path:}";
    String CLUSTER_NAME_PLACEHOLDER = "${nacos.cluster-name:}";
    String ENCODE_PLACEHOLDER = "${nacos.encode:UTF-8}";
    String CONFIG_LONG_POLL_TIMEOUT_PLACEHOLDER = "${nacos.configLongPollTimeout:}";
    String CONFIG_RETRY_TIME_PLACEHOLDER = "${nacos.configRetryTime:}";
    String MAX_RETRY_PLACEHOLDER = "${nacos.maxRetry:}";
    String ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER = "${nacos.enableRemoteSyncConfig:}";
    String USERNAME_PLACEHOLDER = "${nacos.username:}";
    String PASSWORD_PLACEHOLDER = "${nacos.password:}";

    String endpoint() default "${nacos.endpoint:}";

    String namespace() default "${nacos.namespace:}";

    String accessKey() default "${nacos.access-key:}";

    String secretKey() default "${nacos.secret-key:}";

    String serverAddr() default "${nacos.server-addr:}";

    String contextPath() default "${nacos.context-path:}";

    String clusterName() default "${nacos.cluster-name:}";

    String encode() default "${nacos.encode:UTF-8}";

    String configLongPollTimeout() default "${nacos.configLongPollTimeout:}";

    String configRetryTime() default "${nacos.configRetryTime:}";

    String maxRetry() default "${nacos.maxRetry:}";

    String enableRemoteSyncConfig() default "${nacos.enableRemoteSyncConfig:}";

    String username() default "${nacos.username:}";

    String password() default "${nacos.password:}";
}

我想不用做过多的解释

有关Spring 中使用Nacos配置管理的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. ruby - i18n Assets 管理/翻译 UI - 2

    我正在使用i18n从头开始​​构建一个多语言网络应用程序,虽然我自己可以处理一大堆yml文件,但我说的语言(非常)有限,最终我想寻求外部帮助帮助。我想知道这里是否有人在使用UI插件/gem(与django上的django-rosetta不同)来处理多个翻译器,其中一些翻译器不愿意或无法处理存储库中的100多个文件,处理语言数据。谢谢&问候,安德拉斯(如果您已经在ruby​​onrails-talk上遇到了这个问题,我们深表歉意) 最佳答案 有一个rails3branchofthetolkgem在github上。您可以通过在Gemfi

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

随机推荐