当前位置: 首页 > news >正文

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后台看见注册的服务了

http://www.lryc.cn/news/259660.html

相关文章:

  • 开源IPad Pro应用IDE:使用SSH远程连接服务器进行云端编程开发
  • ubuntu 自动安装 MKL Intel fortran 编译器 ifort 及完美平替
  • elementui select中添加新增标签
  • 图像截屏公式识别——LaTeX-OCR安装与使用
  • LabVIEW与Tektronix示波器实现电源测试自动化
  • 青少年CTF-Crypto(Morse code/ASCII和凯撒)
  • Vue3-16-【v-model】 表单数据绑定
  • 【Flink on k8s】- 12 - Flink kubernetes operator 的高级特性
  • 量子芯片技术:未来的计算革命
  • vaptcha-手势验证码
  • 【一种用opencv实现高斯曲线拟合的方法】
  • find_package 和 find_library的区别
  • socket是如何进行通信的
  • STM32-固件打包部署
  • 微信机器人如何使用?好用吗?好奇
  • ARMV8 - A64 - 函数调用,内存栈操作
  • MyBatis 四大核心组件之 ResultSetHandler 源码解析
  • docker-compose 单机容器编排
  • springboot项目使用Layui作为前端UI的一系列前后端交互的解决方法
  • 【Linux】Firewalld防火墙新增端口、开启、查看等
  • 学习笔记 -- TVS管选型参考
  • 功能更新|免费敏捷工具Leangoo领歌私有部署新增第三方身份认证和API对接
  • 重生奇迹mu战士加点
  • 【数据结构(十一·多路查找树)】B树、B+树、B*树(6)
  • 弟弟的作业
  • 代码随想录算法训练营第37天|● 738.单调递增的数字 ● 968.监控二叉树 ● 总结
  • 出现 java: 找不到符号 符号: 变量 log 的解决方法
  • 大数据机器学习与深度学习—— 生成对抗网络(GAN)
  • vue前端访问Django channels WebSocket失败
  • 厉害了!水浸监控技术有升级啦