nacos 定义上下线接口
版本:2021.0.1.0
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>2021.0.1</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2021.0.1.0</version> <type>pom</type> <scope>import</scope> </dependency>
代码
import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.cloud.nacos.NacosServiceManager; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class NacosController { protected final transient Logger log = LoggerFactory.getLogger(getClass()); @Autowired NacosDiscoveryProperties nacosDiscoveryProperties; @Autowired NacosServiceManager nacosServiceManager; /** * 服务注册接口 */ @GetMapping(value = "/api/nacos/register") public String registerInstance() throws NacosException { String serviceName = nacosDiscoveryProperties.getService(); String groupName = nacosDiscoveryProperties.getGroup(); String clusterName = nacosDiscoveryProperties.getClusterName(); String ip = nacosDiscoveryProperties.getIp(); int port = nacosDiscoveryProperties.getPort(); NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties()); log.info("register from nacos, serviceName:{}, groupName:{}, clusterName:{}, ip:{}, port:{}", serviceName, groupName, clusterName, ip, port); namingService.registerInstance(serviceName,groupName,ip,port,clusterName); return "success"; } /** * 服务注销接口 */ @GetMapping(value = "/api/nacos/deregister") public String deregisterInstance() throws NacosException { String serviceName = nacosDiscoveryProperties.getService(); String groupName = nacosDiscoveryProperties.getGroup(); String clusterName = nacosDiscoveryProperties.getClusterName(); String ip = nacosDiscoveryProperties.getIp(); int port = nacosDiscoveryProperties.getPort(); NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties()); log.info("deregister from nacos, serviceName:{}, groupName:{}, clusterName:{}, ip:{}, port:{}", serviceName, groupName, clusterName, ip, port); namingService.deregisterInstance(serviceName,groupName,ip,port,clusterName); return "success"; } }
可用于服务的手动上下线,但因为客户端缓存等问题,deregister 调用后需要sleep 30- 60s,然后进行重启