最近公司项目要上线正式版,里面用到了另一个服务的字典等接口。就需要在上线的时候把字典服务也同步注册到生产的nacos中。在之前的测试环境里,服务注册到了nacos的public命名空间中,字典服务也是在对应nacos的public中,这种只需要在server-addr中添加两个nacos的地址,做成集群就行,但是要部署到生产中的时候,生产服务和字典服务他们的nacos、命名空间都不是同一个,集群的这种方式就不行了,这时就需要一种能将服务注册到不同nacos的不同命名空间中的方法。经过自己长时间的寻找,发现只通过配置是不能做到这一效果的,只能通过添加代码的方式来完成。最后找到了这样的方法,你可以在启动类main方法或重写run方法下添加该代码:
// 创建Nacos客户端配置
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "nacos1-ip:port,nacos2-ip:port");
properties.put(PropertyKeyConst.NAMESPACE, "namespace1");
// 创建NamingService实例
NamingService namingService = NacosFactory.createNamingService(properties);
// 注册服务到第一个命名空间
Instance instance1 = new Instance();
instance1.setIp("your-service-ip");
instance1.setPort(8080);
namingService.registerInstance("your-service-name", instance1);
// 切换到第二个命名空间
properties.put(PropertyKeyConst.NAMESPACE, "namespace2");
namingService = NacosFactory.createNamingService(properties);
// 注册服务到第二个命名空间
Instance instance2 = new Instance();
instance2.setIp("your-service-ip");
instance2.setPort(8080);
namingService.registerInstance("your-service-name", instance2);
上面这种就是在启动后通过代码注册到了两个nacos的不同命名空间中。其中端口、ip、命名空间还有服务名称是必须要加的。在加上你配置文件中的nacos配置,一共就有了三个nacos的注册。但是注意,配置文件中的nacos注册是不能去掉的。所以,针对我的需求,最后的改动如下
// 创建Nacos客户端配置
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "生产nacos地址");
properties.put(PropertyKeyConst.NAMESPACE, "命名空间id");
// 创建NamingService实例
NamingService namingService = NacosFactory.createNamingService(properties);
// 注册服务到第一个命名空间
Instance instance1 = new Instance();
instance1.setIp("注册服务的IP地址");
instance1.setPort(端口);
namingService.registerInstance("服务名称", instance1);
只需要一个配置,加上配置文件中的nacos配置,一共两个,符合了我现在的需求。最后记得将配置文件同步到每个nacos中一份,不然无法启动,但是这里还要注意一点:你的服务走的配置文件还是你项目配置文件中配置nacos里的那个配置文件,代码注册的nacos中的配置文件并不会启用。