版本: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; /** * 服务注册接口 * * @return */ @GetMapping(value = "/api/nacos/register") public String registerInstance() { 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); try { namingService.registerInstance(serviceName,ip,port); } catch (NacosException e) { log.error("register from nacos error", e); return "error"; } return "success"; } /** * 服务注销接口 * * @return */ @GetMapping(value = "/api/nacos/deregister") public String deregisterInstance() { 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); try { namingService.deregisterInstance(serviceName,ip,port); } catch (NacosException e) { log.error("deregister from nacos error", e); return "error"; } return "success"; } }
可用于服务的手动上下线,但因为客户端缓存等问题,deregister 调用后需要sleep 30- 60s,然后进行重启
标签:String,nacos,接口,serviceName,nacosDiscoveryProperties,import,port,定义 From: https://www.cnblogs.com/dongma/p/17336043.html