文章目录
前言
Feign是声明式的web service客户端,它让微服务的调用变得更简单了,类似Controller调用service。SpringCloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端。
只需要创建一个接口,然后添加注解即可
提示:以下是本篇文章正文内容,下面案例可供参考
一、Feign和Resttemplate的区别
Resttemplate需要先定义一个Resttemplate的类注册到bean中使用
同时在进行服务调用的时候要进行url的拼接。
Feign可以伪装成类似SpringMVC的controller一样,将rest的请求进行隐藏,不用再自己拼接url和参数,可以便捷优雅地调用HTTP API
二、通过Feign进行服务调用的步骤
1.创建一个消费者客户端的maven项目
2.创建yml文件
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
#设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
#指的是建立连接后从服务器读取到可用资源所用的时间
ReadTimeout: 5000
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ConnectTimeout: 3000
logging:
level:
# feign日志以什么级别监控哪个接口
com.jyl.springcloud.service.FeignPaymentService: debug
3.创建config日志增强工具
@Configuration
public class FeignConfig
{
@Bean
Logger.Level feignLoggerLevel()
{
return Logger.Level.FULL;
}
}
4.创建Feign的调用接口
其中getPaymentById是服务端的方法,GetMapping也是服务端地址。
@Component
@FeignClient(value = "cloud-payment-service") //Feign客户端的注解,不能漏。value中是服务提供者的名称
public interface FeignPaymentService {
@GetMapping("/payment/getserial/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id);
}
5.创建controller层以及相关类
这里的controller就和平时写的一样了,通过Feign接口进行调用。
@RestController
public class FeignOrderController {
@Resource
private FeignPaymentService feignPaymentService;
@GetMapping("/consumer/payment/getserial/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id){
return feignPaymentService.getPaymentById(id);
}
}