nacos 配置中心示例
导入jar包
<!-- 导入的最新版本为2.3.7.RELEASE -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
jar 包使用说明:
# spring cloud版本(spring-cloud-starter-alibaba-nacos-config)
nacos原生注解(如@NacosValue等)获取不到值,可使用spring注解(如@Value等)读取配置;
# springboot版本(nacos-config-spring-boot-starter)
可使用nacos原生注解、spring注解读取nacos server中的数据,需注意jar包的兼容性
spring 注解
@ConfigurationProperties:常标注在类上,对类进行配置
@Target({ElementType.TYPE, ElementType.METHOD}) //标注在类、方法上
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConfigurationProperties {
@AliasFor("prefix")
String value() default ""; //配置前缀,与prefix等效
@AliasFor("value")
String prefix() default ""; //配置前缀
boolean ignoreInvalidFields() default false;
boolean ignoreUnknownFields() default true;
}
@Value:常标注在字段上,为字段注入值
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
String value();
}
@RefreshScope:动态刷新属性
@Target({ElementType.TYPE, ElementType.METHOD}) //标注在类、方法上
@Retention(RetentionPolicy.RUNTIME)
@Scope("refresh")
@Documented
public @interface RefreshScope {
ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;
}
nacos 注解
@NacosConfigurationProperties:标注在类上,对类进行配置
@Target({ElementType.TYPE}) //标注在类上
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NacosConfigurationProperties {
String prefix() default "";
String groupId() default "DEFAULT_GROUP";
String dataId();
/** @deprecated */
@Deprecated
boolean yaml() default false;
ConfigType type() default ConfigType.PROPERTIES; //配置中心数据格式
boolean autoRefreshed() default false;
boolean ignoreInvalidFields() default false;
boolean ignoreNestedProperties() default false;
boolean ignoreUnknownFields() default true;
boolean exceptionIfInvalid() default true;
NacosProperties properties() default @NacosProperties; //配置中心属性
}
ConfigType:配置中心数据格式
public enum ConfigType {
PROPERTIES("properties"),
XML("xml"),
JSON("json"),
TEXT("text"),
HTML("html"),
YAML("yaml");
String type;
private ConfigType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
}
NacosProperties:配置中心属性
@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:}";
}
@NacosValue:注入值,可标注在字段、方法、方法参数、注解上
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NacosValue {
String value();
boolean autoRefreshed() default false;
}
@NacosProperty
@Target({ElementType.FIELD}) //标注在字段上
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NacosProperty {
String value();
}
@NacosIgnore:忽略字段
@Target({ElementType.FIELD}) //标注在字段上
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NacosIgnore {
}
@NacosConfigListener:配置监听,标注在方法上
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD}) //标注在方法上
@Documented
public @interface NacosConfigListener {
String groupId() default "DEFAULT_GROUP";
String dataId();
ConfigType type() default ConfigType.PROPERTIES;
Class<? extends NacosConfigConverter> converter() default NacosConfigConverter.class;
NacosProperties properties() default @NacosProperties;
long timeout() default 1000L;
}
NacosConfigConverter:配置数据转换
public interface NacosConfigConverter<T> {
boolean canConvert(Class<T> var1);
T convert(String var1);
}
使用示例
bootstrap.yml
spring:
application:
name: nacos-config
cloud:
nacos:
config:
server-addr: localhost:8848
prefix: test
Person
@Data
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
}
HelloController
@RestController
public class HelloController {
@Resource
private Person person;
@RequestMapping("/hello")
public Person hello(){
System.out.println(person);
return person;
}
}
nacos 配置中心
************
使用测试
localhost:8080/hello,控制台输出:
2022-03-11 10:14:48.808 INFO 2790 --- [g.push.receiver] com.alibaba.nacos.client.naming : new ips(1) service: DEFAULT_GROUP@@nacos-config@@DEFAULT -> [{"instanceId":"192.168.5.5#8080#DEFAULT#DEFAULT_GROUP@@nacos-config","ip":"192.168.5.5","port":8080,"weight":1.0,"healthy":true,"enabled":true,"ephemeral":true,"clusterName":"DEFAULT","serviceName":"DEFAULT_GROUP@@nacos-config","metadata":{"dubbo.metadata-service.urls":"[ \"dubbo://192.168.5.5:20880/com.alibaba.cloud.dubbo.service.DubboMetadataService?anyhost=true&application=nacos-config&bind.ip=192.168.5.5&bind.port=20880&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=nacos-config&interface=com.alibaba.cloud.dubbo.service.DubboMetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=2790&qos.enable=false&release=2.7.8&revision=2.2.2.RELEASE&side=provider×tamp=1646964888002&version=1.0.0\" ]","preserved.register.source":"SPRING_CLOUD","dubbo.protocols.dubbo.port":"20880"},"ipDeleteTimeout":30000,"instanceHeartBeatInterval":5000,"instanceHeartBeatTimeOut":15000}]
2022-03-11 10:14:48.813 WARN 2790 --- [client.listener] a.c.d.m.r.DubboServiceMetadataRepository : Current application will subscribe all services(size:1) in registry, a lot of memory and CPU cycles may be used, thus it's strongly recommend you using the externalized property 'dubbo.cloud.subscribed-services' to specify the services
2022-03-11 10:14:48.814 INFO 2790 --- [g.push.receiver] com.alibaba.nacos.client.naming : current ips:(1) service: DEFAULT_GROUP@@nacos-config@@DEFAULT -> [{"instanceId":"192.168.5.5#8080#DEFAULT#DEFAULT_GROUP@@nacos-config","ip":"192.168.5.5","port":8080,"weight":1.0,"healthy":true,"enabled":true,"ephemeral":true,"clusterName":"DEFAULT","serviceName":"DEFAULT_GROUP@@nacos-config","metadata":{"dubbo.metadata-service.urls":"[ \"dubbo://192.168.5.5:20880/com.alibaba.cloud.dubbo.service.DubboMetadataService?anyhost=true&application=nacos-config&bind.ip=192.168.5.5&bind.port=20880&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=nacos-config&interface=com.alibaba.cloud.dubbo.service.DubboMetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=2790&qos.enable=false&release=2.7.8&revision=2.2.2.RELEASE&side=provider×tamp=1646964888002&version=1.0.0\" ]","preserved.register.source":"SPRING_CLOUD","dubbo.protocols.dubbo.port":"20880"},"ipDeleteTimeout":30000,"instanceHeartBeatInterval":5000,"instanceHeartBeatTimeOut":15000}]
2022-03-11 10:14:48.922 INFO 2790 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-03-11 10:14:48.923 INFO 2790 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-03-11 10:14:48.937 INFO 2790 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 14 ms
Person(name=瓜田李下, age=20)