1、是什么?
Fegin是一个声明式WebService客户端。使用Fegin能让编写Web Service 客户端更加简单,它的使用方法是 定义一个接口,然后在上面添加注解即可,同时支持JAX-RS标准的注解。Feign也支持可拔插式的编码器和解码器。SpringCloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。可参考官网: https://github.com/OpenFeign/feign
【1】、修改pom.xml
利用Ribbon维护了MicroServiceCloud-Dept的服务列表信息,并且通过轮询实现了客户端的负载均衡。而与Ribbon不同的是,通过feign只需要定义服务绑定接口且以声明式的方法,优雅而简单的实现了服务调用。
Fegin是一个声明式WebService客户端。使用Fegin能让编写Web Service 客户端更加简单,它的使用方法是 定义一个接口,然后在上面添加注解即可,同时支持JAX-RS标准的注解。Feign也支持可拔插式的编码器和解码器。SpringCloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。可参考官网: https://github.com/OpenFeign/feign
2、能干什么?
Fegin指在使编写Java Http客户端变的容易
使用Ribbon+RestTemplate时,利用RestTemplate对http请求的封装处理,形成了一套模板化的调用方式。但实际开发中,由于对服务的依赖调用可能不止一处,往往一个接口会被多出调用,所以通常会针对每个微服务自行封装一些客户端类来包装这些依赖服务的调用。所以Fegin字此基础上做了进一步封装,由它来帮助我们定义和实现依赖服务接口的定义。在Feign的实现下,我们只需要创建一个接口并使用注解的方式来配置它(以前是Dao接口上面添加Mapper注解,现在是一个微服务接口上面标注一个Feign注解),即可完成服务提供方的接口绑定,简化使用Spring Cloud Ribbon时,自动封装服务调用客户的开发量。
3、实操:
1)、根据microservicecloud-consumer-dept-80创建microservicecloud-consumer-dept-feign微服务
2)、修改microservicecloud-consumer-dept-feign模块的pom.xml文件中添加feign
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
3)、修改microservicecloud-api工程(公共的工程)
【1】、修改pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
【2】、在公共microservicecloud-api模块添加DeptClientService接口并新增注解@FeignClient
@FeignClient(value = "MICROSERVICECLOUD-DEPT",fallbackFactory=DeptClientServiceFallbackFactory.class)
public interface DeptClientService
{
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
public Dept get(@PathVariable("id") long id);
@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
public List<Dept> list();
@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
public boolean add(Dept dept);
}
【3】、maven clear
【4】、maven install
@RestController
public class DeptController_Consumer
{
@Autowired
private DeptClientService service;
@RequestMapping(value = "/consumer/dept/get/{id}")
public Dept get(@PathVariable("id") Long id)
{
return this.service.get(id);
}
@RequestMapping(value = "/consumer/dept/list")
public List<Dept> list()
{
return this.service.list();
}
@RequestMapping(value = "/consumer/dept/add")
public Object add(Dept dept)
{
return this.service.add(dept);
}
}
5)、microservicecloud-consumer-dept-feign工程修改主配置类
@EnableFeignClients(basePackages= {"com.atguigu.springcloud"})
public class DeptConsumer80_Feign_App
{
4、总结:Feign集成了Ribbon
利用Ribbon维护了MicroServiceCloud-Dept的服务列表信息,并且通过轮询实现了客户端的负载均衡。而与Ribbon不同的是,通过feign只需要定义服务绑定接口且以声明式的方法,优雅而简单的实现了服务调用。