搭建客户端,调用eureka上注册的服务方的接口
public class UserController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient; // eureka客户端,可以获取到eureka中服务的信息
@GetMapping
@ResponseBody
public User queryUserById(@RequestParam("id") Long id){
// User user = this.restTemplate.getForObject("http://localhost:9081/user/" + id, User.class);
// return user;
// 根据服务名称,获取服务实例。有可能是集群,所以是service实例集合
List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
// 因为只有一个Service-provider。所以获取第一个实例
ServiceInstance instance = instances.get(0);
// 获取ip和端口信息,拼接成服务地址
String baseUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/user/" + id;
User user = this.restTemplate.getForObject(baseUrl, User.class);
return user;
}
}
配置eureka客户端,注入DiscoveryClient报错,异常信息:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-04-01 13:57:15.520 ERROR 13832 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field discoveryClient in com.example.consumer.controller.UserController required a bean of type 'com.netflix.discovery.DiscoveryClient' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.netflix.discovery.DiscoveryClient' in your configuration.
Disconnected from the target VM, address: '127.0.0.1:4792', transport: 'socket'
Process finished with exit code 1
解决方案:引入jar包问题
import org.springframework.cloud.client.discovery.DiscoveryClient;