1. 使用 @EnableDiscoveryClient 注解标注引导类
package com.study.cloudlearning;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
@RefreshScope
@EnableDiscoveryClient
@SpringBootApplication
public class CloudLearningApplication {
public static void main(String[] args) {
SpringApplication.run(CloudLearningApplication.class, args);
}
}
2. 注入 DiscoveryClient Bean 对象
private DiscoveryClient discoveryClient;
@Autowired
public void setDiscoveryClient(DiscoveryClient discoveryClient) {
this.discoveryClient = discoveryClient;
}
3. 通过 DiscoveryClient 查找指定服务
List<ServiceInstance> organizationInstances = discoveryClient
.getInstances("organization-service");
RestTemplate restTemplate = new RestTemplate();
Organization organization = organizationInstances.stream()
.findFirst()
.map(ServiceInstance::getUri)
.map(uri -> uri + "/v1/organization/{organizationId}")
.map(serviceUri -> restTemplate.getForObject(
serviceUri,
Organization.class,
organizationId)
).orElse(null);