一.利用OpenFeign优化restTemplate

<1>引入依赖

  <!--openFeign-->
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
  </dependency>
  <!--负载均衡器-->
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-loadbalancer</artifactId>
  </dependency>

<2>添加启动注解

<3>配置openfeignClient接口

@FeignClient("item-service")
public interface ItemClient {
    @GetMapping("/items")
    Set<ItemDTO> queryItemByIds(Set<Long> ids);
}

<4>实现远程调用

 Set<ItemDTO> items = itemClient.queryItemByIds(itemIds);

二.启用连接池优化OpenFeign

Feign底层发起http请求,依赖于其它的框架。其底层支持的http客户端实现包括:

  • HttpURLConnection:默认实现,不支持连接池

  • Apache HttpClient :支持连接池

  • OKHttp:支持连接池

因此我们通常会使用带有连接池的客户端来代替默认的HttpURLConnection。比如,我们使用OK Http.

1.引入依赖

<!--OK http 的依赖 -->
<dependency>
  <groupId>io.github.openfeign</groupId>
  <artifactId>feign-okhttp</artifactId>
</dependency>

2.配置连接池

feign:
  okhttp:
    enabled: true # 开启OKHttp功能

三.微服务架构的最佳实践------避免重复编码

  • 思路1:抽取到微服务之外的公共module

  • 思路2:每个微服务自己抽取一个module

思路1抽取更加简单,工程结构也比较清晰,但缺点是整个项目耦合度偏高。

思路2抽取相对麻烦,工程结构相对更复杂,但服务之间耦合度降低。

由于item-service已经创建好,无法继续拆分,因此这里我们采用方案1.

大型项目往往采用思路2,因为其耦合度更低

四.OpenFeign进一步优化----开启日志配置

OpenFeign只会在FeignClient所在包的日志级别为DEBUG时,才会输出日志。而且其日志级别有4级:

  • NONE:不记录任何日志信息,这是默认值。

  • BASIC:仅记录请求的方法,URL以及响应状态码和执行时间

  • HEADERS:在BASIC的基础上,额外记录了请求和响应的头信息

  • FULL:记录所有请求和响应的明细,包括头信息、请求体、元数据。

Feign默认的日志级别就是NONE,所以默认我们看不到请求日志。

1.修改日志配置为debug

logging:
  level:
    com.hmall.api: debug

2.编写配置类

package com.hmall.api.config;

import feign.Logger;
import org.springframework.context.annotation.Bean;

public class DefaultFeignConfig {
    @Bean
    public Logger.Level feignLogLevel(){
        return Logger.Level.FULL;
    }
}

3.局部生效 or 全局生效

  • 局部生效:在某个FeignClient中配置,只对当前FeignClient生效

@FeignClient(value = "item-service", configuration = DefaultFeignConfig.class)
  • 全局生效:在@EnableFeignClients中配置,针对所有FeignClient生效。

@EnableFeignClients(defaultConfiguration = DefaultFeignConfig.class)

更多推荐