Java 不使用springboot注册到nacos2.5.1

一、pom

<!-- Nacos client -->
    <dependency>
        <groupId>com.alibaba.nacos</groupId>
        <artifactId>nacos-client</artifactId>
        <version>2.5.1</version>
    </dependency>

二、demo

public class NacosRegistration {
    public static void main(String[] args) {
        try {
            // 创建配置属性
            Properties properties = new Properties();
            properties.put("serverAddr", "127.0.0.1:8848"); // Nacos服务器地址
        properties.put("username", "nacos");
        properties.put("password", "nacos");

            // 创建NamingService实例
            NamingService naming = NacosFactory.createNamingService(properties);

        InetAddress localhost = InetAddress.getLocalHost();

            // 创建服务实例信息
            Instance instance = new Instance();
            instance.setIp(localhost.getHostAddress()); // 实例IP地址
            instance.setPort(8080); // 实例端口号
            instance.setWeight(1.0); // 权重,默认为1.0,可以根据需要进行设置
            instance.setHealthy(true); // 健康状态,默认为true,表示健康
            instance.setServiceName("example-service"); // 服务名称
            // 注册实例到Nacos服务列表中
            naming.registerInstance("example-service", instance);
      // 核心修改:添加groupName参数
          // namingService.registerInstance(serviceName, groupName, instance);

System.out.println(
"Service registered successfully."); } catch (NacosException e) { e.printStackTrace(); } } }

 ps:

 // 命名空间(public命名空间可省略)
        if (NAMESPACE != null && !NAMESPACE.isEmpty()) {
            properties.put(PropertyKeyConst.NAMESPACE, NAMESPACE);
        }

 

posted @ 2025-10-24 15:58  都是城市惹的祸  阅读(17)  评论(0)    收藏  举报