草庐IT

【Nacos】@NacosValue的使用与原理

morris131 2023-04-10 原文

在SpringCloud工程中,可以使用@RefreshScope+@Value实现配置文件内容变更后的动态刷新。

在SpringBoot工程中,可以使用@NacosValue来实现配置文件内容变更后的动态刷新。

@NacosValue的使用

引入依赖:

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

配置文件增加配置:

nacos:
  config:
    server-addr: 127.0.0.1:8848
    bootstrap:
      enable: true
      log:
        enable: true
    data-id: order-service
    type: yaml
    auto-refresh: true # 开启自动刷新

@NacosValue的例子:

package com.morris.order.controller;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("order")
public class NacosValueController {

    @NacosValue(value = "${user.age}", autoRefreshed = true)
    private Integer age2;

    @GetMapping("age2")
    public Integer getAge2() {
        return age2;
    }

}

注意在SpringCloud项目中不能使用@NacosValue注解,虽然这个注解存在,但是其源码的实现不存在。

@NacosValue源码分析

NacosConfigEnvironmentProcessor

NacosConfigEnvironmentProcessor实现了EnvironmentPostProcessor,会在SpringBoot项目启动时调用postProcessEnvironment()方法,去Nacos配置中心拉取配置。

需要在配置文件中开启预加载nacos.config.bootstrap.enable=true

com.alibaba.boot.nacos.config.autoconfigure.NacosConfigEnvironmentProcessor#postProcessEnvironment

public void postProcessEnvironment(ConfigurableEnvironment environment,
								   SpringApplication application) {
	application.addInitializers(new NacosConfigApplicationContextInitializer(this));
	nacosConfigProperties = NacosConfigPropertiesUtils
		.buildNacosConfigProperties(environment);
	if (enable()) {
		// nacos.config.bootstrap.enable=true
		System.out.println(
			"[Nacos Config Boot] : The preload log configuration is enabled");
		loadConfig(environment);
		NacosConfigLoader nacosConfigLoader = NacosConfigLoaderFactory.getSingleton(nacosConfigProperties, environment, builder);
		LogAutoFreshProcess.build(environment, nacosConfigProperties, nacosConfigLoader, builder).process();
	}
}

com.alibaba.boot.nacos.config.autoconfigure.NacosConfigEnvironmentProcessor#loadConfig

private void loadConfig(ConfigurableEnvironment environment) {
	NacosConfigLoader configLoader = new NacosConfigLoader(nacosConfigProperties,
														   environment, builder);
	configLoader.loadConfig();
	// set defer NacosPropertySource
	deferPropertySources.addAll(configLoader.getNacosPropertySources());
}

从配置中心拉取配置加入到Environment。
com.alibaba.boot.nacos.config.util.NacosConfigLoader#loadConfig

public void loadConfig() {
	MutablePropertySources mutablePropertySources = environment.getPropertySources();
	List<NacosPropertySource> sources = reqGlobalNacosConfig(globalProperties,
															 nacosConfigProperties.getType());
	for (NacosConfigProperties.Config config : nacosConfigProperties.getExtConfig()) {
		List<NacosPropertySource> elements = reqSubNacosConfig(config,
															   globalProperties, config.getType());
		sources.addAll(elements);
	}
	if (nacosConfigProperties.isRemoteFirst()) {
		// 默认为false,默认本地的配置优先级高
		for (ListIterator<NacosPropertySource> itr = sources.listIterator(sources.size()); itr.hasPrevious();) {
			mutablePropertySources.addAfter(
				StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, itr.previous());
		}
	} else {
		for (NacosPropertySource propertySource : sources) {
			mutablePropertySources.addLast(propertySource);
		}
	}
}

NacosConfigApplicationContextInitializer

NacosConfigApplicationContextInitializer注册负责监听Nacos配置,实现自动刷新配置

com.alibaba.boot.nacos.config.autoconfigure.NacosConfigApplicationContextInitializer#initialize

public void initialize(ConfigurableApplicationContext context) {
	singleton.setApplicationContext(context);
	environment = context.getEnvironment();
	nacosConfigProperties = NacosConfigPropertiesUtils
		.buildNacosConfigProperties(environment);
	final NacosConfigLoader configLoader = NacosConfigLoaderFactory.getSingleton(
		nacosConfigProperties, environment, builder);
	if (!enable()) {
		logger.info("[Nacos Config Boot] : The preload configuration is not enabled");
	}
	else {

		// If it opens the log level loading directly will cache
		// DeferNacosPropertySource release

		if (processor.enable()) {
			// nacos.config.bootstrap.enable=true
			processor.publishDeferService(context);
			// 添加监听器
			configLoader
				.addListenerIfAutoRefreshed(processor.getDeferPropertySources());
		}
		else {
			configLoader.loadConfig();
			configLoader.addListenerIfAutoRefreshed();
		}
	}

	final ConfigurableListableBeanFactory factory = context.getBeanFactory();
	if (!factory
		.containsSingleton(NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME)) {
		factory.registerSingleton(NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME,
								  configLoader.getGlobalProperties());
	}
}

遍历所有的Nacos配置文件,每个配置文件都添加一个监听器。
com.alibaba.boot.nacos.config.util.NacosConfigLoader#addListenerIfAutoRefreshed(java.util.List<com.alibaba.boot.nacos.config.util.NacosConfigLoader.DeferNacosPropertySource>)

public void addListenerIfAutoRefreshed(
	final List<DeferNacosPropertySource> deferNacosPropertySources) {
	for (DeferNacosPropertySource deferNacosPropertySource : deferNacosPropertySources) {
		NacosPropertySourcePostProcessor.addListenerIfAutoRefreshed(
			deferNacosPropertySource.getNacosPropertySource(),
			deferNacosPropertySource.getProperties(),
			deferNacosPropertySource.getEnvironment());
	}
}

要实现配置的自动刷新,需要在配置文件中开启nacos.config.auto-refresh=true
com.alibaba.nacos.spring.core.env.NacosPropertySourcePostProcessor#addListenerIfAutoRefreshed

public static void addListenerIfAutoRefreshed(
	final NacosPropertySource nacosPropertySource, final Properties properties,
	final ConfigurableEnvironment environment) {

	// nacos.config.auto-refresh=true
	if (!nacosPropertySource.isAutoRefreshed()) { // Disable Auto-Refreshed
		return;
	}

	final String dataId = nacosPropertySource.getDataId();
	final String groupId = nacosPropertySource.getGroupId();
	final String type = nacosPropertySource.getType();
	final NacosServiceFactory nacosServiceFactory = getNacosServiceFactoryBean(
		beanFactory);

	try {

		ConfigService configService = nacosServiceFactory
			.createConfigService(properties);

		Listener listener = new AbstractListener() {

			@Override
			public void receiveConfigInfo(String config) {
				String name = nacosPropertySource.getName();
				NacosPropertySource newNacosPropertySource = new NacosPropertySource(
					dataId, groupId, name, config, type);
				newNacosPropertySource.copy(nacosPropertySource);
				MutablePropertySources propertySources = environment
					.getPropertySources();
				// replace NacosPropertySource
				// 监听事件的处理,直接替换Environment中的配置
				propertySources.replace(name, newNacosPropertySource);
			}
		};

		if (configService instanceof EventPublishingConfigService) {
			// 通过EventPublishingConfigService进行代理
			((EventPublishingConfigService) configService).addListener(dataId,
																	   groupId, type, listener);
		}
		else {
			configService.addListener(dataId, groupId, listener);
		}

	}
	catch (NacosException e) {
		throw new RuntimeException(
			"ConfigService can't add Listener with properties : " + properties,
			e);
	}
}

通过EventPublishingConfigService添加监听器,里面对监听器做了一层包装。
com.alibaba.nacos.spring.context.event.config.EventPublishingConfigService#addListener(java.lang.String, java.lang.String, java.lang.String, com.alibaba.nacos.api.config.listener.Listener)

public void addListener(String dataId, String group, String type, Listener listener)
	throws NacosException {
	Listener listenerAdapter = new DelegatingEventPublishingListener(configService,
																	 dataId, group, type, applicationEventPublisher, executor, listener);
	addListener(dataId, group, listenerAdapter);
}

当配置中心的配置变更后,首先会回调DelegatingEventPublishingListener的receiveConfigInfo(),这里会调用被代理的监听器的receiveConfigInfo(),还会发布NacosConfigReceivedEvent事件。
com.alibaba.nacos.spring.context.event.config.DelegatingEventPublishingListener#receiveConfigInfo

public void receiveConfigInfo(String content) {
	// 调用被代理的监听器的receiveConfigInfo()
	onReceived(content);
	// 发布NacosConfigReceivedEvent事件
	publishEvent(content);
}

private void publishEvent(String content) {
	NacosConfigReceivedEvent event = new NacosConfigReceivedEvent(configService,
																  dataId, groupId, content, configType);
	applicationEventPublisher.publishEvent(event);
}

private void onReceived(String content) {
	delegate.receiveConfigInfo(content);
}

NacosValueAnnotationBeanPostProcessor

postProcessPropertyValues()

NacosValueAnnotationBeanPostProcessor实现了InstantiationAwareBeanPostProcessorAdapter,其postProcessBeforeInitialization()方法会在Bean实例化之后和初始化之前执行,对Bean上加了@NacosValue注解的属性进行设置。

com.alibaba.spring.beans.factory.annotation.AbstractAnnotationBeanPostProcessor#postProcessPropertyValues

public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
	// 查找@NacosVaLue注解的属性和方法
	InjectionMetadata metadata = this.findInjectionMetadata(beanName, bean.getClass(), pvs);

	try {
		// 为属性设置值
		metadata.inject(bean, beanName, pvs);
		return pvs;
	} catch (BeanCreationException var7) {
		throw var7;
	} catch (Throwable var8) {
		throw new BeanCreationException(beanName, "Injection of @" + this.getAnnotationType().getSimpleName() + " dependencies is failed", var8);
	}
}

postProcessBeforeInitialization()

NacosValueAnnotationBeanPostProcessor实现了BeanPostProcessor,其postProcessBeforeInitialization()方法会在Bean实例化之后和初始化之前执行,主要负责收集带有@NacosValue注解且需要自动刷新的属性。

如果属性需要自动刷新,需要设置@NacosValue的autoRefreshed为true。

com.alibaba.nacos.spring.context.annotation.config.NacosValueAnnotationBeanPostProcessor#postProcessBeforeInitialization

public Object postProcessBeforeInitialization(Object bean, final String beanName)
	throws BeansException {

	// 对Bean所有的属性进行处理
	doWithFields(bean, beanName);

	// 对Bean所有的方法进行处理
	doWithMethods(bean, beanName);

	return super.postProcessBeforeInitialization(bean, beanName);
}

private void doWithFields(final Object bean, final String beanName) {
	ReflectionUtils.doWithFields(bean.getClass(),
								 new ReflectionUtils.FieldCallback() {
									 @Override
									 public void doWith(Field field) throws IllegalArgumentException {
										 NacosValue annotation = getAnnotation(field, NacosValue.class);
										 doWithAnnotation(beanName, bean, annotation, field.getModifiers(),
														  null, field);
									 }
								 });
}

private void doWithAnnotation(String beanName, Object bean, NacosValue annotation,
							  int modifiers, Method method, Field field) {
	if (annotation != null) {
		if (Modifier.isStatic(modifiers)) {
			return;
		}

		if (annotation.autoRefreshed()) {
			String placeholder = resolvePlaceholder(annotation.value());

			if (placeholder == null) {
				return;
			}

			NacosValueTarget nacosValueTarget = new NacosValueTarget(bean, beanName,
																	 method, field, annotation.value());
			// 将带有@NacosValue注解的属性加入到一个Map中
			put2ListMap(placeholderNacosValueTargetMap, placeholder,
						nacosValueTarget);
		}
	}
}

监听NacosConfigReceivedEvent

收到NacosConfigReceivedEvent事件时,通过反射调用上面收集好的属性和方法从而实现自动刷新。

com.alibaba.nacos.spring.context.annotation.config.NacosValueAnnotationBeanPostProcessor#onApplicationEvent

public void onApplicationEvent(NacosConfigReceivedEvent event) {
	// In to this event receiver, the environment has been updated the
	// latest configuration information, pull directly from the environment
	// fix issue #142
	for (Map.Entry<String, List<NacosValueTarget>> entry : placeholderNacosValueTargetMap
		 .entrySet()) {
		String key = environment.resolvePlaceholders(entry.getKey());
		String newValue = environment.getProperty(key);

		if (newValue == null) {
			continue;
		}
		List<NacosValueTarget> beanPropertyList = entry.getValue();
		for (NacosValueTarget target : beanPropertyList) {
			String md5String = MD5Utils.md5Hex(newValue, "UTF-8");
			boolean isUpdate = !target.lastMD5.equals(md5String);
			if (isUpdate) {
				target.updateLastMD5(md5String);
				Object evaluatedValue = resolveNotifyValue(target.nacosValueExpr, key, newValue);
				if (target.method == null) {
					setField(target, evaluatedValue);
				}
				else {
					setMethod(target, evaluatedValue);
				}
			}
		}
	}
}

有关【Nacos】@NacosValue的使用与原理的更多相关文章

  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. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

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

  8. 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

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

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

  10. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

随机推荐