【Spring Cloud Alibaba】Nacos的服务注册和发现(discovery)的使用
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class NacosDiscoveryController {
@NacosInjected
private NamingService namingService;
@Autowired
private NamingService namingService2;
@GetMapping("/registerInstance")
public String registerInstance(@RequestParam String serviceName,
@RequestParam String ip,
@RequestParam int port) throws NacosException {
namingService.registerInstance(serviceName, ip, port);
return "Instance registered.";
}
@GetMapping("/deregisterInstance")
public String deregisterInstance(@RequestParam String serviceName,
@RequestParam String ip,
@RequestParam int port) throws NacosException {
namingService.deregisterInstance(serviceName, ip, port);
return "Instance de-registered.";
}
// 使用NacosInjected和Autowired的示例
@GetMapping("/injectedExample")
public String injectedExample() {
if (namingService == namingService2) {
return "NamingService instances are equal.";
} else {
return "NamingService instances are not equal.";
}
}
}
这段代码演示了如何在Spring Boot应用中使用Nacos作为服务注册和发现的组件。它提供了两个API接口来注册和注销服务实例,并演示了如何使用@NacosInjected
和@Autowired
注入NamingService
实例。通过这个示例,开发者可以学习如何在实际的生产环境中使用Nacos作为服务注册中心。
评论已关闭