nacos 使用说明
??????????
??????????????
?????????????????????????????????
相关依赖
????????????
<!-- 注册中心依赖 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 配置中心依赖 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
?????????????
????????????????
?????????????????????????????????
注册中心
?????? ????
自动配置类:META-INF/spring.factories
???? ? ?? ?? ? ?? ?
# 注册中心自动配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration,\ #服务发现自动配置类
com.alibaba.cloud.nacos.ribbon.RibbonNacosAutoConfiguration,\
com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpointAutoConfiguration,\
com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration,\ #服务注册自动配置类
com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration,\
com.alibaba.cloud.nacos.discovery.reactive.NacosReactiveDiscoveryClientConfiguration,\
com.alibaba.cloud.nacos.discovery.configclient.NacosConfigServerAutoConfiguration,\ #配置中心自动配置类(使用的是spring cloud的配置中心,推荐使用nacos配置中心)
com.alibaba.cloud.nacos.NacosServiceAutoConfiguration
# 启动配置
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.alibaba.cloud.nacos.discovery.configclient.NacosDiscoveryClientConfigServiceBootstrapConfiguration
????????????
NacosServiceAutoConfiguration:nacos服务自动配置类
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnDiscoveryEnabled
@ConditionalOnNacosDiscoveryEnabled
public class NacosServiceAutoConfiguration {
public NacosServiceAutoConfiguration() {
}
@Bean
public NacosServiceManager nacosServiceManager() {
return new NacosServiceManager();
} //创建nacos服务管理器
}
????????????????
NacosServiceManager:nacos服务管理器
public class NacosServiceManager {
private NacosDiscoveryProperties nacosDiscoveryPropertiesCache;
private NamingService namingService;
private NamingMaintainService namingMaintainService;
public NacosServiceManager() {
}
public NamingService getNamingService(Properties properties) {
if (Objects.isNull(this.namingService)) {
this.buildNamingService(properties);
}
return this.namingService;
}
public NamingMaintainService getNamingMaintainService(Properties properties) {
if (Objects.isNull(this.namingMaintainService)) {
this.buildNamingMaintainService(properties);
}
return this.namingMaintainService;
}
public boolean isNacosDiscoveryInfoChanged(NacosDiscoveryProperties nacosDiscoveryProperties) {
if (!Objects.isNull(this.nacosDiscoveryPropertiesCache) && !this.nacosDiscoveryPropertiesCache.equals(nacosDiscoveryProperties)) {
BeanUtils.copyProperties(nacosDiscoveryProperties, this.nacosDiscoveryPropertiesCache);
return true;
} else {
return false;
}
}
private NamingMaintainService buildNamingMaintainService(Properties properties) {
if (Objects.isNull(this.namingMaintainService)) {
Class var2 = NacosServiceManager.class;
synchronized(NacosServiceManager.class) {
if (Objects.isNull(this.namingMaintainService)) {
this.namingMaintainService = this.createNamingMaintainService(properties);
}
}
}
return this.namingMaintainService;
}
private NamingService buildNamingService(Properties properties) {
if (Objects.isNull(this.namingService)) {
Class var2 = NacosServiceManager.class;
synchronized(NacosServiceManager.class) {
if (Objects.isNull(this.namingService)) {
this.namingService = this.createNewNamingService(properties);
}
}
}
return this.namingService;
}
private NamingService createNewNamingService(Properties properties) {
try {
return NacosFactory.createNamingService(properties);
} catch (NacosException var3) {
throw new RuntimeException(var3);
}
}
private NamingMaintainService createNamingMaintainService(Properties properties) {
try {
return NacosFactory.createMaintainService(properties);
} catch (NacosException var3) {
throw new RuntimeException(var3);
}
}
public void reBuildNacosService(Properties nacosProperties) {
this.namingService = this.createNewNamingService(nacosProperties);
this.namingMaintainService = this.createNamingMaintainService(nacosProperties);
}
public void nacosServiceShutDown() throws NacosException {
this.namingService.shutDown();
}
@EventListener
public void onInstancePreRegisteredEvent(InstancePreRegisteredEvent instancePreRegisteredEvent) {
Registration registration = instancePreRegisteredEvent.getRegistration();
if (Objects.isNull(this.nacosDiscoveryPropertiesCache) && registration instanceof NacosRegistration) {
NacosDiscoveryProperties nacosDiscoveryProperties = ((NacosRegistration)registration).getNacosDiscoveryProperties();
this.nacosDiscoveryPropertiesCache = new NacosDiscoveryProperties();
BeanUtils.copyProperties(nacosDiscoveryProperties, this.nacosDiscoveryPropertiesCache);
}
}
}
????????????
??????????????
NacosServiceRegistryAutoConfiguration:服务注册自动配置类
@Configuration(
proxyBeanMethods = false
)
@EnableConfigurationProperties
@ConditionalOnNacosDiscoveryEnabled
@ConditionalOnProperty(
value = {"spring.cloud.service-registry.auto-registration.enabled"},
matchIfMissing = true
)
@AutoConfigureAfter({AutoServiceRegistrationConfiguration.class, AutoServiceRegistrationAutoConfiguration.class, NacosDiscoveryAutoConfiguration.class})
public class NacosServiceRegistryAutoConfiguration {
public NacosServiceRegistryAutoConfiguration() {
}
@Bean
public NacosServiceRegistry nacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties, NacosServiceManager nacosServiceManager) {
return new NacosServiceRegistry(nacosDiscoveryProperties, nacosServiceManager);
} //创建NacosServiceRegistry,进行服务注册、卸载、设置健康状态等
@Bean
@ConditionalOnBean({AutoServiceRegistrationProperties.class})
public NacosRegistration nacosRegistration(ObjectProvider<List<NacosRegistrationCustomizer>> registrationCustomizers, NacosDiscoveryProperties nacosDiscoveryProperties, ApplicationContext context) {
return new NacosRegistration((List)registrationCustomizers.getIfAvailable(), nacosDiscoveryProperties, context);
}
@Bean
@ConditionalOnBean({AutoServiceRegistrationProperties.class})
public NacosAutoServiceRegistration nacosAutoServiceRegistration(NacosServiceRegistry registry, AutoServiceRegistrationProperties autoServiceRegistrationProperties, NacosRegistration registration) {
return new NacosAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration);
}
}
???????????
NacosServiceRegistry:注册卸载服务、设置获取服务状态等
public class NacosServiceRegistry implements ServiceRegistry<Registration> {
private static final Logger log = LoggerFactory.getLogger(NacosServiceRegistry.class);
private final NacosDiscoveryProperties nacosDiscoveryProperties;
private NacosServiceManager nacosServiceManager;
public NacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties, NacosServiceManager nacosServiceManager) {
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
this.nacosServiceManager = nacosServiceManager;
}
public void register(Registration registration) { //注册服务
if (StringUtils.isEmpty(registration.getServiceId())) {
log.warn("No service to register for nacos client...");
} else {
NamingService namingService = this.namingService();
String serviceId = registration.getServiceId();
String group = this.nacosDiscoveryProperties.getGroup();
Instance instance = this.getNacosInstanceFromRegistration(registration);
try {
namingService.registerInstance(serviceId, group, instance); //使用namingService注册服务
log.info("nacos registry, {} {} {}:{} register finished", new Object[]{group, serviceId, instance.getIp(), instance.getPort()});
} catch (Exception var7) {
log.error("nacos registry, {} register failed...{},", new Object[]{serviceId, registration.toString(), var7});
ReflectionUtils.rethrowRuntimeException(var7);
}
}
}
public void deregister(Registration registration) { //卸载服务
log.info("De-registering from Nacos Server now...");
if (StringUtils.isEmpty(registration.getServiceId())) {
log.warn("No dom to de-register for nacos client...");
} else {
NamingService namingService = this.namingService();
String serviceId = registration.getServiceId();
String group = this.nacosDiscoveryProperties.getGroup();
try {
namingService.deregisterInstance(serviceId, group, registration.getHost(), registration.getPort(), this.nacosDiscoveryProperties.getClusterName());
//使用namingService卸载服务
} catch (Exception var6) {
log.error("ERR_NACOS_DEREGISTER, de-register failed...{},", registration.toString(), var6);
}
log.info("De-registration finished.");
}
}
public void close() {
try {
this.nacosServiceManager.nacosServiceShutDown();
} catch (NacosException var2) {
log.error("Nacos namingService shutDown failed", var2);
}
}
public void setStatus(Registration registration, String status) { //设置服务状态
if (!status.equalsIgnoreCase("UP") && !status.equalsIgnoreCase("DOWN")) {
log.warn("can't support status {},please choose UP or DOWN", status);
} else {
String serviceId = registration.getServiceId();
Instance instance = this.getNacosInstanceFromRegistration(registration);
if (status.equalsIgnoreCase("DOWN")) {
instance.setEnabled(false);
} else {
instance.setEnabled(true);
}
try {
Properties nacosProperties = this.nacosDiscoveryProperties.getNacosProperties();
this.nacosServiceManager.getNamingMaintainService(nacosProperties).updateInstance(serviceId, instance);
} catch (Exception var6) {
throw new RuntimeException("update nacos instance status fail", var6);
}
}
}
public Object getStatus(Registration registration) { //获取服务状态
String serviceName = registration.getServiceId();
try {
List<Instance> instances = this.namingService().getAllInstances(serviceName);
Iterator var4 = instances.iterator();
while(var4.hasNext()) {
Instance instance = (Instance)var4.next();
if (instance.getIp().equalsIgnoreCase(this.nacosDiscoveryProperties.getIp()) && instance.getPort() == this.nacosDiscoveryProperties.getPort()) {
return instance.isEnabled() ? "UP" : "DOWN";
}
}
} catch (Exception var6) {
log.error("get all instance of {} error,", serviceName, var6);
}
return null;
}
private Instance getNacosInstanceFromRegistration(Registration registration) {
Instance instance = new Instance();
instance.setIp(registration.getHost());
instance.setPort(registration.getPort());
instance.setWeight((double)this.nacosDiscoveryProperties.getWeight());
instance.setClusterName(this.nacosDiscoveryProperties.getClusterName());
instance.setEnabled(this.nacosDiscoveryProperties.isInstanceEnabled());
instance.setMetadata(registration.getMetadata());
instance.setEphemeral(this.nacosDiscoveryProperties.isEphemeral());
return instance;
} //获取服务实例
private NamingService namingService() {
return this.nacosServiceManager.getNamingService(this.nacosDiscoveryProperties.getNacosProperties());
} //通过nacosServiceManager获取namingService
}
????????????
???????????????
NacosDiscoveryAutoConfiguration:服务发现自动配置类
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnDiscoveryEnabled
@ConditionalOnNacosDiscoveryEnabled
public class NacosDiscoveryAutoConfiguration {
public NacosDiscoveryAutoConfiguration() {
}
@Bean
@ConditionalOnMissingBean
public NacosDiscoveryProperties nacosProperties() {
return new NacosDiscoveryProperties();
} //创建NacosDiscoveryProperties
@Bean
@ConditionalOnMissingBean
public NacosServiceDiscovery nacosServiceDiscovery(NacosDiscoveryProperties discoveryProperties, NacosServiceManager nacosServiceManager) {
return new NacosServiceDiscovery(discoveryProperties, nacosServiceManager);
} //创建NacosServiceDiscovery
}
??????????????
NacosDiscoveryProperties:服务发现配置属性类
@ConfigurationProperties("spring.cloud.nacos.discovery")
public class NacosDiscoveryProperties {
private static final Logger log = LoggerFactory.getLogger(NacosDiscoveryProperties.class);
public static final String PREFIX = "spring.cloud.nacos.discovery";
private static final Pattern PATTERN = Pattern.compile("-(\\w)");
private String serverAddr;
private String username;
private String password;
private String endpoint;
private String namespace;
private long watchDelay = 30000L;
private String logName;
@Value("${spring.cloud.nacos.discovery.service:${spring.application.name:}}")
private String service;
private float weight = 1.0F;
private String clusterName = "DEFAULT";
private String group = "DEFAULT_GROUP";
private String namingLoadCacheAtStart = "false";
private Map<String, String> metadata = new HashMap();
private boolean registerEnabled = true;
private String ip;
private String networkInterface = "";
private int port = -1;
private boolean secure = false;
private String accessKey;
private String secretKey;
private Integer heartBeatInterval;
private Integer heartBeatTimeout;
private Integer ipDeleteTimeout;
private boolean instanceEnabled = true;
private boolean ephemeral = true;
@Autowired
private InetUtils inetUtils;
@Autowired
private Environment environment;
@Autowired
private NacosServiceManager nacosServiceManager;
@Autowired
private Optional<NacosAutoServiceRegistration> nacosAutoServiceRegistrationOptional;
public NacosDiscoveryProperties() {
}
???????????????
NacosServiceDiscovery:获取对象列表
public class NacosServiceDiscovery {
private NacosDiscoveryProperties discoveryProperties;
private NamingService namingService;
public NacosServiceDiscovery(NacosDiscoveryProperties discoveryProperties, NacosServiceManager nacosServiceManager) {
this.discoveryProperties = discoveryProperties;
this.namingService = nacosServiceManager.getNamingService(discoveryProperties.getNacosProperties());
}
public List<ServiceInstance> getInstances(String serviceId) throws NacosException {
//获取ServiceInstance对象列表
String group = this.discoveryProperties.getGroup();
List<Instance> instances = this.namingService.selectInstances(serviceId, group, true);
return hostToServiceInstanceList(instances, serviceId);
}
public List<String> getServices() throws NacosException { //获取服务
String group = this.discoveryProperties.getGroup();
ListView<String> services = this.namingService.getServicesOfServer(1, 2147483647, group);
return services.getData();
}
public static List<ServiceInstance> hostToServiceInstanceList(List<Instance> instances, String serviceId) {
//将instances列表转换为ServiceInstance列表
List<ServiceInstance> result = new ArrayList(instances.size());
Iterator var3 = instances.iterator();
while(var3.hasNext()) {
Instance instance = (Instance)var3.next();
ServiceInstance serviceInstance = hostToServiceInstance(instance, serviceId);
if (serviceInstance != null) {
result.add(serviceInstance);
}
}
return result;
}
public static ServiceInstance hostToServiceInstance(Instance instance, String serviceId) {
//将instance转换为ServiceInstance
if (instance != null && instance.isEnabled() && instance.isHealthy()) {
NacosServiceInstance nacosServiceInstance = new NacosServiceInstance();
nacosServiceInstance.setHost(instance.getIp());
nacosServiceInstance.setPort(instance.getPort());
nacosServiceInstance.setServiceId(serviceId);
Map<String, String> metadata = new HashMap();
metadata.put("nacos.instanceId", instance.getInstanceId());
metadata.put("nacos.weight", instance.getWeight() + "");
metadata.put("nacos.healthy", instance.isHealthy() + "");
metadata.put("nacos.cluster", instance.getClusterName() + "");
if (instance.getMetadata() != null) {
metadata.putAll(instance.getMetadata());
}
metadata.put("nacos.ephemeral", String.valueOf(instance.isEphemeral()));
nacosServiceInstance.setMetadata(metadata);
if (metadata.containsKey("secure")) {
boolean secure = Boolean.parseBoolean((String)metadata.get("secure"));
nacosServiceInstance.setSecure(secure);
}
return nacosServiceInstance;
} else {
return null;
}
}
}
???????????
?????????????
?????????????????????????????????
配置中心
?????? ?
************
自动配置类
??
META-INF/spring.factories
???? ? ?? ?? ? ?? ?
# 启动配置类
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.alibaba.cloud.nacos.NacosConfigBootstrapConfiguration
# 自动配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.alibaba.cloud.nacos.NacosConfigAutoConfiguration,\
com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration
org.springframework.boot.diagnostics.FailureAnalyzer=\
com.alibaba.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureAnalyzer
? ? ? ? ? ? ? ? ?
NacosConfigAutoConfiguration
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnProperty(
name = {"spring.cloud.nacos.config.enabled"},
matchIfMissing = true
)
public class NacosConfigAutoConfiguration {
public NacosConfigAutoConfiguration() {
}
@Bean
public NacosConfigProperties nacosConfigProperties(ApplicationContext context) {
return context.getParent() != null && BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getParent(), NacosConfigProperties.class).length > 0 ? (NacosConfigProperties)BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(), NacosConfigProperties.class) : new NacosConfigProperties();
} //创建NacosConfigProperties
@Bean
public NacosRefreshProperties nacosRefreshProperties() {
return new NacosRefreshProperties();
} //创建NacosRefreshProperties,该类已禁用,直接在NacosConfigurationProperties设置
@Bean
public NacosRefreshHistory nacosRefreshHistory() {
return new NacosRefreshHistory();
}
@Bean
public NacosConfigManager nacosConfigManager(NacosConfigProperties nacosConfigProperties) {
return new NacosConfigManager(nacosConfigProperties);
} //创建NacosConfigManager(配置管理器)
@Bean
public NacosContextRefresher nacosContextRefresher(NacosConfigManager nacosConfigManager, NacosRefreshHistory nacosRefreshHistory) {
return new NacosContextRefresher(nacosConfigManager, nacosRefreshHistory);
} //创建NacosContextRefresher(刷新配置)
}
?????????????
NacosConfigProperties
@ConfigurationProperties("spring.cloud.nacos.config")
public class NacosConfigProperties {
public static final String PREFIX = "spring.cloud.nacos.config";
public static final String COMMAS = ",";
public static final String SEPARATOR = "[,]";
private static final Pattern PATTERN = Pattern.compile("-(\\w)");
private static final Logger log = LoggerFactory.getLogger(NacosConfigProperties.class);
@Autowired
@JsonIgnore
private Environment environment;
private String serverAddr;
private String username;
private String password;
private String encode;
private String group = "DEFAULT_GROUP";
private String prefix;
private String fileExtension = "properties";
private int timeout = 3000;
private String maxRetry;
private String configLongPollTimeout;
private String configRetryTime;
private boolean enableRemoteSyncConfig = false;
private String endpoint;
private String namespace;
private String accessKey;
private String secretKey;
private String contextPath;
private String clusterName;
private String name;
private List<NacosConfigProperties.Config> sharedConfigs;
private List<NacosConfigProperties.Config> extensionConfigs;
private boolean refreshEnabled = true; //是否刷新,默认true
public NacosConfigProperties() {
}
??????????
NacosRefreshProperties:是否刷新,该类已禁用,直接在NacosConfigProperties中设置
@Deprecated //已禁用
@Component
public class NacosRefreshProperties {
@Value("${spring.cloud.nacos.config.refresh.enabled:true}")
private boolean enabled = true;
public NacosRefreshProperties() {
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
??????????????
NacosConfigManager:配置管理器
public class NacosConfigManager {
private static final Logger log = LoggerFactory.getLogger(NacosConfigManager.class);
private static ConfigService service = null;
private NacosConfigProperties nacosConfigProperties;
public NacosConfigManager(NacosConfigProperties nacosConfigProperties) {
this.nacosConfigProperties = nacosConfigProperties;
createConfigService(nacosConfigProperties);
}
static ConfigService createConfigService(NacosConfigProperties nacosConfigProperties) {
//创建configService,进行配置操作
if (Objects.isNull(service)) {
Class var1 = NacosConfigManager.class;
synchronized(NacosConfigManager.class) {
try {
if (Objects.isNull(service)) {
service = NacosFactory.createConfigService(nacosConfigProperties.assembleConfigServiceProperties());
}
} catch (NacosException var4) {
log.error(var4.getMessage());
throw new NacosConnectionFailureException(nacosConfigProperties.getServerAddr(), var4.getMessage(), var4);
}
}
}
return service;
}
public ConfigService getConfigService() {
if (Objects.isNull(service)) {
createConfigService(this.nacosConfigProperties);
}
return service;
}
public NacosConfigProperties getNacosConfigProperties() {
return this.nacosConfigProperties;
}
}
???????????
ConfigService:发布更新、获取、删除、监听配置(实现类NacosConfigService)
public interface ConfigService {
boolean publishConfig(String var1, String var2, String var3) throws NacosException;
boolean removeConfig(String var1, String var2) throws NacosException;
String getConfig(String var1, String var2, long var3) throws NacosException;
String getConfigAndSignListener(String var1, String var2, long var3, Listener var5) throws NacosException;
void addListener(String var1, String var2, Listener var3) throws NacosException;
void removeListener(String var1, String var2, Listener var3);
String getServerStatus();
void shutDown() throws NacosException;
}
?????????????????
NacosContextRefresher:上下文刷新
public class NacosContextRefresher implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {
private static final Logger log = LoggerFactory.getLogger(NacosContextRefresher.class);
private static final AtomicLong REFRESH_COUNT = new AtomicLong(0L);
private NacosConfigProperties nacosConfigProperties;
private final boolean isRefreshEnabled;
private final NacosRefreshHistory nacosRefreshHistory;
private final ConfigService configService;
private ApplicationContext applicationContext;
private AtomicBoolean ready = new AtomicBoolean(false);
private Map<String, Listener> listenerMap = new ConcurrentHashMap(16);
public NacosContextRefresher(NacosConfigManager nacosConfigManager, NacosRefreshHistory refreshHistory) {
this.nacosConfigProperties = nacosConfigManager.getNacosConfigProperties();
this.nacosRefreshHistory = refreshHistory;
this.configService = nacosConfigManager.getConfigService();
this.isRefreshEnabled = this.nacosConfigProperties.isRefreshEnabled();
}
/** @deprecated */
@Deprecated
public NacosContextRefresher(NacosRefreshProperties refreshProperties, NacosRefreshHistory refreshHistory, ConfigService configService) {
this.isRefreshEnabled = refreshProperties.isEnabled();
this.nacosRefreshHistory = refreshHistory;
this.configService = configService;
}
public void onApplicationEvent(ApplicationReadyEvent event) {
if (this.ready.compareAndSet(false, true)) {
this.registerNacosListenersForApplications();
}
}
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
private void registerNacosListenersForApplications() { //注册监听器
if (this.isRefreshEnabled()) {
Iterator var1 = NacosPropertySourceRepository.getAll().iterator();
while(var1.hasNext()) {
NacosPropertySource propertySource = (NacosPropertySource)var1.next();
if (propertySource.isRefreshable()) {
String dataId = propertySource.getDataId();
this.registerNacosListener(propertySource.getGroup(), dataId);
}
}
}
}
private void registerNacosListener(final String groupKey, final String dataKey) {
String key = NacosPropertySourceRepository.getMapKey(dataKey, groupKey);
Listener listener = (Listener)this.listenerMap.computeIfAbsent(key, (lst) -> {
return new AbstractSharedListener() {
public void innerReceive(String dataId, String group, String configInfo) {
NacosContextRefresher.refreshCountIncrement();
NacosContextRefresher.this.nacosRefreshHistory.addRefreshRecord(dataId, group, configInfo);
NacosContextRefresher.this.applicationContext.publishEvent(new RefreshEvent(this, (Object)null, "Refresh Nacos config"));
if (NacosContextRefresher.log.isDebugEnabled()) {
NacosContextRefresher.log.debug(String.format("Refresh Nacos config group=%s,dataId=%s,configInfo=%s", group, dataId, configInfo));
}
}
};
});
try {
this.configService.addListener(dataKey, groupKey, listener);
} catch (NacosException var6) {
log.warn(String.format("register fail for nacos listener ,dataId=[%s],group=[%s]", dataKey, groupKey), var6);
}
}
public NacosConfigProperties getNacosConfigProperties() {
return this.nacosConfigProperties;
}
public NacosContextRefresher setNacosConfigProperties(NacosConfigProperties nacosConfigProperties) {
this.nacosConfigProperties = nacosConfigProperties;
return this;
}
public boolean isRefreshEnabled() {
if (null == this.nacosConfigProperties) {
return this.isRefreshEnabled;
} else {
return this.nacosConfigProperties.isRefreshEnabled() && !this.isRefreshEnabled ? false : this.isRefreshEnabled;
}
}
public static long getRefreshCount() {
return REFRESH_COUNT.get();
}
public static void refreshCountIncrement() {
REFRESH_COUNT.incrementAndGet();
}
}
????????????
************
相关注解
@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);
}
???????????
???????????
|