java集成Nacos服务
1,添加依赖:首先,在你的 Java 项目中,你需要添加 Nacos 客户端 SDK 的依赖
<dependency><groupId>com.alibaba.nacos</groupId><artifactId>nacos-client</artifactId><version>2.1.1</version></dependency>
2,编写注册代码:接下来,你可以编写 Java 代码来将服务注册到 Nacos 服务注册中心并连接到指定的命名空间
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;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.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;/*** Java集成Nacos服务 * Nacos版本 2.1.1* @author YannanGao 20231214*/
public class NacosTest {static ExecutorService executorService = Executors.newFixedThreadPool(1);public static void main(String[] args) throws NacosException, InterruptedException {String clusterName = "DEFAULT";// 指定 clusterNameString serverAddr= "127.0.0.1:" + 8848;// Nacos 服务ip地址String localIpAddress = getLocalIpAddress(true);// 本机内网ipString namesPace="gs-test";//命名空间// 创建连接 Nacos 服务注册中心的配置Properties properties = new Properties();properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);// 指定ip 端口properties.put(PropertyKeyConst.NAMESPACE, namesPace); // 指定命名空间properties.put(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START, "false"); // 用于指定是否在启动时加载缓存。当设置为 true 时,Nacos// 客户端在启动时会从 Nacos// 服务端加载服务实例信息到本地缓存中,以提高后续的查询性能。properties.put(PropertyKeyConst.CLUSTER_NAME, clusterName); // 指定 clusterName// 创建 Nacos 服务注册中心的连接NamingService namingService = NamingFactory.createNamingService(properties);String serviceName = "test-service-java";// 服务名称int httpPort = 80;// 当前项目http端口// 创建服务实例Instance instance = new Instance();instance.setIp(localIpAddress);instance.setPort(httpPort);instance.setServiceName(serviceName);Map<String, String> map = new HashMap<String, String>();map.put("realIp", localIpAddress);map.put("info", "自定义内容");instance.setMetadata(map);// 元数据// 注册服务实例到 Nacos 服务注册中心namingService.registerInstance(serviceName, instance);System.err.println("Nacos 注册成功!");//获取指定服务名的实例列表getAllInstances("hall", namingService);// 创建并注册关闭钩子Runtime.getRuntime().addShutdownHook(new Thread(() -> {System.err.println("监听到程序关闭了");// 关闭Nacos连接try {executorService.shutdown();namingService.deregisterInstance(serviceName, localIpAddress, httpPort, clusterName);System.err.println("Nacos 注销成功!");} catch (NacosException e) {// TODO Auto-generated catch blocke.printStackTrace();}}));//获取指定分组的配置文件String dataId = "app_common";String group = "init";getConfig(serverAddr, dataId, group,clusterName,namesPace);//监听定分组的配置文件变更executorService.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {receiveConfigInfo(serverAddr, dataId, group,clusterName,namesPace);} catch (NacosException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});while (true) {Thread.sleep(1000 * 10);System.err.println("...");}}/*** 获取指定服务名的实例列表* @param serviceName* @param namingService*/public static void getAllInstances(String serviceName,NamingService namingService) {try {// 获取指定服务名的实例列表List<Instance> instances = namingService.getAllInstances(serviceName);// 打印实例的 IP 和端口信息for (Instance instance : instances) {System.out.println(serviceName+" Instance: " + instance.getIp() + ":" + instance.getPort());}} catch (Exception e) {e.printStackTrace();// TODO: handle exception}}/*** 获取配置文件* @param serverAddr* @param dataId* @param group* @param clusterName* @param namesPace*/public static void getConfig(String serverAddr, String dataId, String group,String clusterName,String namesPace) {try {Properties properties = new Properties();properties.put("serverAddr", serverAddr);properties.put(PropertyKeyConst.NAMESPACE, namesPace); // 指定命名空间properties.put(PropertyKeyConst.CLUSTER_NAME, clusterName); // 指定 clusterNameConfigService configService = NacosFactory.createConfigService(properties);String config = configService.getConfig(dataId, group, 5000); // 获取配置文件,5000 表示超时时间,单位为毫秒System.err.println("getConfig Retrieved config: " + config);} catch (Exception e) {e.printStackTrace();// TODO: handle exception}}/*** 监听配置文件更新* @param serverAddr* @param dataId* @param group* @param clusterName* @param namesPace* @throws NacosException*/public static void receiveConfigInfo(String serverAddr, String dataId, String group,String clusterName,String namesPace) throws NacosException {try {Properties properties = new Properties();properties.put("serverAddr", serverAddr);properties.put(PropertyKeyConst.NAMESPACE, namesPace); // 指定命名空间properties.put(PropertyKeyConst.CLUSTER_NAME, clusterName); // 指定 clusterNameConfigService configService = NacosFactory.createConfigService(properties);configService.addListener(dataId, group, new Listener() {@Overridepublic Executor getExecutor() {return null;}@Overridepublic void receiveConfigInfo(String configInfo) {// 处理配置更新的逻辑System.err.println("receiveConfigInfo Received updated config: " + configInfo);}});} catch (Exception e) {e.printStackTrace();// TODO: handle exception}}/*** 获取本机IP**/public static String getLocalIpAddress(boolean local) {String localip = null;// 本地IP,如果没有配置外网IP则返回它String netip = null;// 外网IPEnumeration<NetworkInterface> netInterfaces = null;try {netInterfaces = NetworkInterface.getNetworkInterfaces();} catch (SocketException e) {return null;}InetAddress ip = null;while (netInterfaces.hasMoreElements()) {NetworkInterface ni = netInterfaces.nextElement();Enumeration<InetAddress> address = ni.getInetAddresses();while (address.hasMoreElements()) {ip = address.nextElement();if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IPif (netip == null) {netip = ip.getHostAddress();}} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()&& ip.getHostAddress().indexOf(":") == -1) {// 内网IPif (localip == null) {localip = ip.getHostAddress();}}}}if (local) {return localip;}return netip;}}
3,运行起来就可以Nacos后台看见注册的服务了