Feign介绍
Feign是一个声明式WebService客户端。使用Feign能让编写Web Service客户端更加简单, 它的使用方法是定义一个接口,然后在上面添加注解,同时也支持JAX-RS标准的注解。Feign也支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。
消费者导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
编写接口
加上@FeignClient(value = “MICROSERVICECLOUD-DEPT”)注解
@FeignClient(value = "MICROSERVICECLOUD-DEPT")//value=微服务的名字
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);
}
调用者主启动类加上扫描使用了@FeignClient注解的类
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages= {“com.atguigu.springcloud”})
@ComponentScan(“com.atguigu.springcloud”)
直接调用
@RestController
public class DeptController_Feign
{
@Autowired
private DeptClientService service = null;
@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);
}
}
总结
Feign通过接口的方法调用Rest服务(之前是Ribbon+RestTemplate),
该请求发送给Eureka服务器(http://MICROSERVICECLOUD-DEPT/dept/list),
通过Feign直接找到服务接口,由于在进行服务调用的时候融合了Ribbon技术,所以也支持负载均衡作用。
Feign是一个声明式WebService客户端,简化了WebService客户端的编写。通过定义接口并添加注解即可实现服务调用,支持JAX-RS标准注解及SpringMVC标准注解。Feign与Eureka和Ribbon结合使用时,能支持负载均衡。
9884

被折叠的 条评论
为什么被折叠?



