第六次课:声明式REST客户端Feign

飞一样的编程
飞一样的编程
擅长邻域:Java,MySQL,Linux,nginx,springboot,mongodb,微信小程序,vue

分类: springboot 专栏: 新版springcloud分布式学习 标签: openfeign

2024-04-29 09:23:40 304浏览

声明式REST客户端Feign

前言

RestTemplate方式调用存在的问题

  • 代码可读性差,编程体验不统一
  • 参数复杂URL难以维护

Feign

Feign是一个声明式的http客户端, 官方地址: https://github.com/OpenFeign/feign

其作用就是帮助我们优雅的实现http请求的发送,解决上面提到的问题。

使用步骤

依赖

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

加@EnableFeignClients

在需要远程调用的微服务的启动类上加注解:@EnableFeignClients

编写feign客户端

编写要远程调用接口的方法签名,主要是基于springMvc的注解声明远程调用的信息

  • 服务名称: user-service
  • 请求方式: GET
  • 请求路径: /user/{id}
  • 请求参数: Long id
  • 返回值类型: User
@FeignClient("user-service")

public interface UserClient {

    @GetMapping("/user/{id}")
    User get(@PathVariable Long id);
}

调用代码

    @Autowired
    UserClient userClient;
    // .....
 	order.setUser(userClient.get(order.getUserId()));

打印日志

先把日志级别调成debug模式

logging:
  level:
  	com.jf3q.feign: debug
  • 全局生效
spring:   
   cloud:
     openfeign:
      client:
        config:
          default: #这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置
            loggerLevel: FULL #日志级别
  • 局部生效
spring:   
   cloud:
     openfeign:
      client:
        config:
         user-service: #这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置
            loggerLevel: FULL #日志级别

性能优化

Feign底层的客户端实现:

  • URLConnection: 默认实现,不支持连接池
  • Apache HttpClient :支持连接池
  • OKHttp:支持连接池

所以我们改用Apache HttpClient ,并且日志级别要么直接不用要么选用BASIC

依赖

 <!--httpclient的依赖-->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
        </dependency>
feign:
  client:
    config:
      default: #这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置
        loggerLevel: BASIC #日志级别
  httpclient:
    enabled: true #开启feign.对HttpClient的支持
    max-connections: 200 #最大的连接数
    max-connections-per-route: 50 #每个路径的最大连接数

抽离feign模块

把feign单独抽离出去成一个模块,打成jar供需要远程调用的微服务注入使用

注意,启动类和feign客户端不在一个模块的时候。要加@EnableFeignClients(clients ={OssClient.class} )

远程调用的时候参数传递失败

这个@RequestParam(name = "path")去掉就传不过来了。

远程调用携带token

写一个配置类

@Configuration
public class FeignConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        requestTemplate.header("token", request.getHeader("token"));
    }
}

然后在feign客户端加configuration属性

@FeignClient(value = "upload-service",configuration = FeignConfig.class)
@RequestMapping("/oss")
public interface UploadClient {

    @DeleteMapping
    ResultDto del(@RequestParam(name = "path") String path);
}

课外补充

如果远程调用的时候传文件的话怎么操作

参考文章:https://blog.csdn.net/weixin_47420368/article/details/114589740


好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695