【Spring Cloud】Nacos 服务注册与发现实践
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class NacosDiscoveryController {
private final DiscoveryClient discoveryClient;
public NacosDiscoveryController(DiscoveryClient discoveryClient) {
this.discoveryClient = discoveryClient;
}
@GetMapping("/services")
public Object services() {
List<String> services = discoveryClient.getServices();
return services;
}
@GetMapping("/instances/{serviceId}")
public List<ServiceInstance> instances(String serviceId) {
return discoveryClient.getInstances(serviceId);
}
}
这段代码定义了一个简单的REST控制器,它使用Spring Cloud提供的DiscoveryClient
来获取服务列表和特定服务实例信息。这是服务注册与发现的一个实际应用案例,可以帮助开发者理解如何在实际的Web应用中使用Nacos作为服务注册中心。
评论已关闭