【Spring Cloud】声明式Feign客户端调用工具
【学习背景】
通过前面的总结学习,我们可以回想下,是通过什么方式做到服务间的调用的?答案是:Ribbon+RestTemplate,且通过@LoadBalanced注解实现了客户端的负载均衡。本篇博客将介绍另一种调用方式,Feign。Feign也使用了ribbon,只要使用@FeignClient时,ribbon就会自动使用。
【学习内容】
1. Feign框架介绍
Feign 是一个声明web服务客户端,这便得编写web服务客户端更容易,使用Feign 创建一个接口并对它进行注解,它具有可插拔的注解支持包括Feign注解与JAX-RS注解,Feign还支持可插拔的编码器与解码器,Spring Cloud 增加了对 Spring MVC的注解,Spring Web 默认使用了HttpMessageConverters, Spring Cloud 集成 Ribbon 和 Eureka 提供的负载均衡的HTTP客户端 Feign.
2. Feign集成demo
添加Feign maven依赖,基于spring boot 2.0版本的依赖如下:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在服务提供者项目中,声明Feign客户端调用接口,调用服务提供者的相关接口:
// 声明调用的服务名称
@FeignClient(name = “eureka-service-provider”)
public interface InvokerApiFeign {@RequestMapping("/user/{userId}")
public String getServiceProvider(@PathVariable(value = "userId") Integer userId);
}
此处需要注意的是参数传递需要添加@PathVaiable注解,用value=””标明对应的参数,否则会抛出IllegalStateException异常。
服务消费者中提供对应的接口
@RestController
public class FeignController {@Autowired
private InvokerApiFeign invokerApiFeign;
@RequestMapping("/user/{userId}")
public String getServiceProvider(@PathVariable Integer userId){
return invokerApiFeign.getServiceProvider(userId);
}
}
在Application启动类上添加@@EnableFeignClients注解
SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class EurekaServiceInvokerApplication {public static void main(String[] args) {
SpringApplication.run(EurekaServiceInvokerApplication.class, args);
}
}
【学习demo】
对应服务消费者项目更新代码github地址:
https://github.com/huzhiting/spring-cloud/tree/master/eureka-service-invoker
【学习总结】
其实通过Feign封装了HTTP调用服务方法,使得客户端像调用本地方法那样直接调用方法,类似Dubbo中暴露远程服务的方式,区别在于Dubbo是基于私有二进制协议,而Feign本质上还是个HTTP客户端。
还没有评论,来说两句吧...