以下配置文件具体可以看nacos 动态读取nacos配置中心项目配置这篇博客中的配置文件(配置文件是统一用的)
简单读取nacos配置中心配置:
package com.richfit.richfit.controller.nacos;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Properties;
import java.util.concurrent.Executor;
@RestController
@RequestMapping("/nacos")
public class nacosController {
//使用@nacosValue注解获取值,并开启自动更新
@NacosValue(value = "${spring.datasource.password}", autoRefreshed = true)
private String urlheadAutoRefresh;
/**
* @NacosValue注解,这种的不能实时读取更新nacos中修改的配置,除非重启项目或者重启nacos。下面这个方法就可以实时更新返回
* @return
*/
@GetMapping("getNacosValue1")
public String getValue1(){
return "getNacosValue1:"+urlheadAutoRefresh;
//输出:getNacosValue1:hlr2261226HLR
}
@Value("${spring.application.name}")
private String name;
@Value("${spring.cloud.nacos.config.file-extension}")
private String extension;
@Value("${spring.cloud.nacos.config.group}")
private String group;
@Value("${spring.cloud.nacos.config.namespace}")
private String namespace;
@Value("${spring.cloud.nacos.config.username}")
private String username;
@Value("${spring.cloud.nacos.config.password}")
private String password;
/**
*
* @return
* @throws NacosException
* @throws InterruptedException
*/
@GetMapping("getNacosValue")
public String getValue() throws NacosException, InterruptedException {
String dataId = name + "."+extension;
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "localhost");
//这一定是命名空间id不能是名称
properties.put(PropertyKeyConst.NAMESPACE, namespace);
properties.put(PropertyKeyConst.USERNAME, username);
properties.put(PropertyKeyConst.PASSWORD, password);
properties.put(PropertyKeyConst.SERVER_NAME,name);
ConfigService configService = NacosFactory.createConfigService(properties);
System.out.println("是否已经连接服务:"+configService.getServerStatus());//是否已经连接服务:UP 代表已连接
if ("UP".equalsIgnoreCase(configService.getServerStatus())) {
System.out.println("Nacos服务状态正常,服务可用。");
// 进行其他业务逻辑处理
} else {
System.out.println("Nacos服务状态异常,服务不可用。");
// 进行错误处理或重试逻辑
}
String content = configService.getConfig(dataId, group, 5000);
System.out.println(content);
//下面为监听器,只要客户端中配置改了,下面的addListener就会触发
configService.addListener(dataId, group, new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
System.out.println("receive:" + configInfo);
}
@Override
public Executor getExecutor() {
return null;
}
});
//content 是 配置的内容,配置后在发布
// boolean isPublishOk = configService.publishConfig(dataId, group, "脸脸真可爱,悦悦很可爱,妞妞太可爱");
// System.out.println(isPublishOk);
//
// Thread.sleep(3000);
// //配置完后在获取
// content = configService.getConfig(dataId, group, 5000);
// System.out.println(content);
return content;
}
}
@NacosValue 读取客户端配置的关键注解
简单读取nacos服务注册和订阅:
package com.richfit.richfit.controller.nacos;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Properties;
/**
* 获取nacos上的服务列表
*
* Nacos为服务注册与发现提供了一个SDK类 NamingService,
* 通过该类,可以实现服务的注册与发现、订阅服务的动态变化、
* 获取服务实例、获取注册中心的健康状态等等
*
* <dependency>
* <groupId>com.alibaba.nacos</groupId>
* <artifactId>nacos-client</artifactId>
* <version>1.4.2</version>
* </dependency>
*
* namingService.registerInstance():注册实例
* namingService.deregisterInstance():取消注册
* namingService.getAllInstances(String serviceName):获取服务的所有实例
* namingService.getServicesOfServer(int pageNo, int pageSize):分页查询,从服务器获取所有服务名称
* namingService.getSubscribeServices():获取当前客户端所有订阅的服务
* namingService.selectInstances():根据条件获取服务实例
* namingService.selectOneHealthyInstance():根据条件选择一个健康的实例
* namingService.subscribe():订阅服务以接收实例更改事件
* namingService.unsubscribe():取消订阅
* namingService.getServerStatus():获取服务器健康状态
*/
@RestController
@RequestMapping("/nacosClient")
public class NacosClient {
@Value("${spring.application.name}")
private String name;
@Value("${spring.cloud.nacos.config.file-extension}")
private String extension;
@Value("${spring.cloud.nacos.config.group}")
private String group;
@Value("${spring.cloud.nacos.config.namespace}")
private String namespace;
@Value("${spring.cloud.nacos.config.username}")
private String username;
@Value("${spring.cloud.nacos.config.password}")
private String password;
/**
*
* @return
* @throws NacosException
* @throws InterruptedException
*/
@GetMapping("getNacosFuwu")
public String getNacosFuwu(){
try {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "localhost:8848");
//这一定是命名空间id不能是名称
properties.put(PropertyKeyConst.NAMESPACE, namespace);
properties.put(PropertyKeyConst.USERNAME, username);
properties.put(PropertyKeyConst.PASSWORD, password);
// 服务名
String serviceName = "richfit.properties";
//properties.put(PropertyKeyConst.SERVER_NAME, serviceName);
NamingService namingService = NacosFactory.createNamingService(properties);
//获取服务器健康状态
String serverStatus = namingService.getServerStatus();
System.out.println("服务器健康状态:"+serverStatus);
//服务注册
namingService.registerInstance(serviceName, "192.168.1.101:", 8888, "richfit-TEST");
//使用namingService获取服务列表
List<Instance> instances = namingService.getAllInstances(serviceName);
// 输出服务列表
for (Instance instance : instances) {
System.out.println("IP: " + instance.getIp());
System.out.println("Port: " + instance.getPort());
//是否健康
System.out.println("Healthy: " + instance.isHealthy());
//Healthy: true
//节点是否存在
System.out.println("Enabled: " + instance.isEnabled());
System.out.println("Weight: " + instance.getWeight());
//Weight: 1.0
System.out.println("ClusterName: " + instance.getClusterName());
//ClusterName: richfit-TEST
System.out.println("InstanceId: " + instance.getInstanceId());
//InstanceId: 192.168.1.101:#8888#richfit-TEST#DEFAULT_GROUP@@richfit.properties
System.out.println("------------------------");
}
//订阅服务以接收实例更改事件
namingService.subscribe("richfit.properties", new EventListener() {
@Override
public void onEvent(Event event) {
// int removeSize = ((NamingChangeEvent) event).instancesDiff.removedInstances.size();
// int addSize = ((NamingChangeEvent) event).instancesDiff.addedInstances.size();
// if (removeSize > 0){
// System.out.println("已取消订阅的服务名:"+((NamingEvent)event).getServiceName());
// }
// if (addSize > 0){
// System.out.println("已新增订阅的服务名:"+((NamingEvent)event).getServiceName());
// }
System.out.println("已订阅的实例:"+((NamingEvent)event).getInstances()+"个服务");
}
});
//获取当前客户端所有订阅的服务。服务订阅之后,当客户端服务列表没有显示节点了,但是一段时间内订阅者列表节点不会消失
List<ServiceInfo> subscribeServices = namingService.getSubscribeServices();
//如果订阅的个数大于0
if (subscribeServices.size() > 0){
try {
//取消服务注册
namingService.deregisterInstance(serviceName, "192.168.1.101:", 8888, "richfit-TEST");
} catch (NacosException e) {
throw new RuntimeException(e);
}
}
System.out.println("获取当前客户端所有订阅的服务个数:"+namingService.getSubscribeServices().size());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}