TZ_14_Feign的客户端和Feign的负载均衡

1.作用:Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的Controller一样。你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做。

 

2.导入起步坐标

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

 

3.在起步器中加入注解@EnableFeignClients

@SpringCloudApplication
@EnableFeignClients
public class ApplicationService {

    public static void main(String[] args) {
        SpringApplication.run(ApplicationService.class);
    }
}

 

 

4.通过Controller调用Feign的客户端的接口  需要请求的方式一致  参数一致  返回类型一致 方法名一致

@RestController
@RequestMapping("User")
public class UserController {
    @Autowired
    private UserFeign userFeign;

    @GetMapping ("{id}")
    public User selectById(@PathVariable("id") Integer id) {return userFeign.findById(id);
    }
}

 

5.创建Feign的客户端的接口

  • 首先这是一个接口,Feign会通过动态代理,帮我们生成实现类。这点跟mybatis的mapper很像

  • @FeignClient,声明这是一个Feign客户端,类似@Mapper注解。同时通过value属性指定服务名称

  • 接口中的定义方法,完全采用SpringMVC的注解,Feign会根据注解帮我们生成URL,并访问获取结果

改造原来的调用逻辑,不再调用UserDao:

@FeignClient(value = "user-service")
public interface UserFeign {
    @GetMapping("/User/{id}")
    User findById(@PathVariable("id") Integer id);

}

 

 

 6.Feign的负载均衡的实现

 1>开启feign的hystrix的熔断器

  application.yaml

feign:
  hystrix:
    enabled: true # 开启Feign的熔断功能

 

2>在frign的客户端接口上自己配置熔断器类  当熔断器打是执行

@FeignClient(value = "user-service",fallback = UserFeignFallback.class)
public interface UserFeign {
    @GetMapping("/User/{id}")
    User findById(@PathVariable("id") Integer id);

}

 

3>熔断的业务逻辑

@Component
public class UserFeignFallback implements UserFeign {
    @Override
    public User findById(Integer id) {
        User user = new User();
        user.setName("未知用户");
        return user;
    }
}

 

 7.请求压缩

Spring Cloud Feign 支持对请求和响应进行GZIP压缩,以减少通信过程中的性能损耗。通过下面的参数即可开启请求与响应的压缩功能:

feign:
  compression:
    request:
      enabled: true # 开启请求压缩
    response:
      enabled: true # 开启响应压缩

 

同时,我们也可以对请求的数据类型,以及触发压缩的大小下限进行设置:

feign:
  compression:
    request:
      enabled: true # 开启请求压缩
      mime-types: text/html,application/xml,application/json # 设置压缩的数据类型
      min-request-size: 2048 # 设置触发压缩的大小下限

 

转载于:https://www.cnblogs.com/asndxj/p/11480738.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值