Feign

欢迎光临我的博客[http://poetize.cn],前端使用Vue2,聊天室使用Vue3,后台使用Spring Boot

Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单。Feign提供了HTTP请求的模板,通过编写简单的接口和插入注解,就可以定义好HTTP请求的参数、格式、地址等信息。
Feign整合了Ribbon和Hystrix

Feign 特性

  1. 可插拔的注解支持,包括Feign注解和JAX-RS注解
  2. 支持可插拔的HTTP编码器和解码器
  3. 支持Hystrix和它的Fallback
  4. 支持Ribbon的负载均衡(feign底层是使用了ribbon作为负载均衡的客户端,而ribbon的负载均衡也是依赖于eureka获得各个服务的地址,所以要引入eureka-client
  5. 支持HTTP请求和响应的压缩

依赖


        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

Feign的使用

  1. 添加依赖
  2. 启动类添加 @EnableFeignClients 注解支持
  3. 建立Client接口,并在接口中定义需调用的服务方法
  4. 使用Client接口。
启动类添加注解支持:
    @EnableFeignClients
    @EnableDiscoveryClient


建立Client接口,并在接口中定义需调用的服务方法

    //FeignClient注解用于指定从哪个服务中调用功能 ,里面的名称与被调用的服务名保持一致,并且不能包含下划线
    @FeignClient(name = "tensquare-base")
    public interface LabelClient {
        @RequestMapping(value="/label/{id}", method = RequestMethod.GET)
        public Result findById(@PathVariable("id") String id);
    }


使用Client接口

    @Autowired
    private LabelClient labelClient;

    @RequestMapping(value = "/label/{labelid}")
    public Result findLabelById(@PathVariable String labelid) {
        Result result = labelClient.findById(labelid);
        return result;
    }

spring cloud 中 discovery service

多种实现(eureka、consul、zookeeper等等):

  1. @EnableDiscoveryClient基于spring-cloud-commons
  2. @EnableEurekaClient基于spring-cloud-netflix
  3. 如果选用的注册中心是eureka,那么就推荐@EnableEurekaClient
  4. 如果是其他的注册中心,那么推荐使用@EnableDiscoveryClient
posted @ 2019-08-30 14:37  LittleDonkey  阅读(226)  评论(0编辑  收藏  举报