SringCloud Feign使用

xiaoxiao2021-02-28  11

springColud目录

Feign简介


Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign, 我们可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到这是远程方法,更感知不到这是个HTTP请求,这整个调用过程和Dubbo的RPC非常类似。开发起来非常的优雅。

Feign 的简单使用


配置依赖 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>

2.入口程序上增加@EnableFeignClients注解

@SpringBootApplication @EnableEurekaClient @EnableFeignClients public class MicroserviceConsumerApplication { public static void main(String[] args) { SpringApplication.run(MicroserviceConsumerApplication.class, args); } }

3.编写接口

首先贴出服务端的代码 在消费端映射的接口代码 // microservice-provider:映射的微服务的虚拟的地址 @FeignClient("microservice-provider") public interface UserFeignClient { @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET) public User findById(@PathVariable("id") Long id); // 有两个坑: //1. @GetMapping不支持,必须直接写出提交的方式是get还是post的 //2. @PathVariable得设置value //只要参数是复杂对象,即使指定了是GET方法,feign依然会以POST方法进行发送请求。如下 //成功 @RequestMapping(value = "/user", method = RequestMethod.POST) public User postUser(@RequestBody User user); //失败 // @RequestMapping(value = "/get-user", method = RequestMethod.GET) // public User getUser(User user); //} 使用该接口 @Autowired private UserFeignClient userFeignClient; @GetMapping("/movief/{id}") public User findByFeginId(@PathVariable Long id) { return userFeignClient.findById(id); }

Feign 的进阶使用


为feign添加配置文件


1.feign的默认配置(摘录自官网文档)

所以在配置文件中可修改的项就有编码,解码方式,日志级别,使用的容器,等Contract(feign容器)配置的是SpringMvc容器,所以在之前的使用中,我们使用的是springmvc的注解@RequestMapping

2.添加配置文件

添加@ExcludeFromComponentScan注解的目的同上一期Ribbon中的目的一致,如果该文件放在主程序的文件目录及子目录下时,spring扫描后会将该策略设置为所有的feign接口使用,所以我们要避免该文件被spring扫描到。配置文件可配的项有 @Configuration @ExcludeFromComponentScan public class FeignConfiguration1 { //这里我们改为了feign的原生容器,则在接口中就不能使用springmvc的注解,要使用feign的原生注解 @Bean public Contract feignContract() { return new Contract.Default(); } //配置fegin的日志级别,要使得日志生效,还得再application.yml中添加配置,见下方feign的日志使用 @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } }

3.修改接口文件

@FeignClient(name = "microservice-provider", configuration = FeignConfiguration1.class) public interface UserFeignClient { //由于FeignConfiguration1中使用原生的容器,这里要使用原生feign注解 //@RequestLine(请求方式+" "+请求路径) //参数必须加上@Param注解 @RequestLine("GET /simple/{id}") public User findById(@Param("id") Long id); }

为feign添加日志监控


1.首先在application.yml添加如下配置

logging: level: com.spongebob.cloud.microserviceconsumer.fegin: DEBUG

2.其次在FeignConfiguration1 文件中添加日志要监控的级别,如上全部监控。

Feign 加入Ribbon 负载均衡


1.Feign 内嵌入了Ribbon 的依赖,不需要再引入依赖 2.在application.xml配置文件中添加如下配置

microservice-provider: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #采用轮询

Feign支持请求和响应的压缩


增加gzip配置 #请求和响应GZIP压缩支持 feign.compression.request.enabled=true feign.compression.response.enabled=true
转载请注明原文地址: https://www.6miu.com/read-1900119.html

最新回复(0)