Nacos能夠?qū)崿F(xiàn)服務(wù)注冊(cè)與發(fā)現(xiàn),在服務(wù)提供者和服務(wù)消費(fèi)者調(diào)用時(shí),使用自帶組件。
1. 在服務(wù)消費(fèi)者中注入DiscoveryClient
@Autowired
private DiscoveryClient discoveryClient;
2. 從discoveryClient中用服務(wù)名字獲取服務(wù)地址
// 從nacos中獲取服務(wù)地址
List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("service_product");
ServiceInstance serviceInstance = serviceInstanceList.get(0);
String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
3. 當(dāng)同一個(gè)服務(wù)有多個(gè)實(shí)例時(shí),自定義實(shí)現(xiàn)負(fù)載均衡
// 從nacos中獲取服務(wù)地址
List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("service_product");
// 自定義負(fù)載均衡
int index = new Random().nextInt(serviceInstanceList.size());
ServiceInstance serviceInstance = serviceInstanceList.get(index);
String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();