SpringBoot集成nacos⽰例
spring怎么读取yaml⼀、引⼊pom
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
⼆、resource⽬录下添加bootstrap.properties
server.port=8080
#命名空间
spring.fig.namespace=xxx
#nacos地址
spring.fig.:x
#配置⽂件⼀
spring.sion-configs[0].data-id=xxx.yaml
spring.sion-configs[0].refresh=true
spring.sion-configs[0].group=DEFAULT_GROUP
#配置⽂件⼆
spring.sion-configs[1].data-id=xxx.yaml
spring.sion-configs[1].refresh=true
spring.sion-configs[1].group=DEFAULT_GROUP
三、读取nacos配置⽂件的⼯具类
import com.alibaba.cloud.nacos.client.NacosPropertySourceBuilder;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import com.alibaba.ption.NacosException;
slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.fig.PropertySourceBootstrapConfiguration;
import org.springframework.fig.PropertySourceLocator;
import org.springframework.stereotype.Component;
import flect.Field;
import java.util.List;
@Component
@Slf4j
public class NacosConfig {
@Autowired
private PropertySourceBootstrapConfiguration propertySourceBootstrapConfiguration;
public String getData(String group,String dataId,long timeout){
try {
Field propertySourceLocators = DeclaredField("propertySourceLocators");
propertySourceLocators.setAccessible(true);
List<PropertySourceLocator> list = (List<PropertySourceLocator>)(propertySourceBootstrapConfiguration);
NacosPropertySourceLocator nacosLocator = null;
for(PropertySourceLocator locator : list){
if(locator instanceof NacosPropertySourceLocator){
nacosLocator = (NacosPropertySourceLocator)locator;
}
}
if(nacosLocator == null){
return null;
}
Field nacosPropertySourceBuilderField = DeclaredField("nacosPropertySourceBuilder");
nacosPropertySourceBuilderField.setAccessible(true);
NacosPropertySourceBuilder nacosPropertySourceBuilder = ((nacosLocator);            String config = ConfigService().getConfig(dataId, group, timeout);
return config;
} catch (NoSuchFieldException | IllegalAccessException | NacosException e) {
<("nacos⼯具异常",e);
}
return null;
}
}
四、在需要⽤到的地⽅注⼊
@Autowired
private  NacosConfig nacosConfig;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。