Field discoveryClient in ××× required a bean of type ‘com

 

搭建客户端,调用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;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值