微服务远程调用-Feign

先来看我们以前利用RestTemplate发起远程调用的代码:

存在下面的问题:

•代码可读性差,编程体验不统一

•参数复杂URL难以维护

 

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

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

 

1、Feign替代RestTemplate

Fegin的使用步骤如下:

1)引入依赖

父工程需要引入依赖(注意springboot、spring cloud、spring cloud alibaba 版本冲突问题)

 

 

 

<properties>
        <java.version>1.8</java.version>
        <spring.boot.dependency.version>2.3.9.RELEASE</spring.boot.dependency.version>
        <spring-cloud-alibaba.dependencies.version>2.2.5.RELEASE</spring-cloud-alibaba.dependencies.version>
        <spring.cloud.dependency.version>Hoxton.SR10</spring.cloud.dependency.version>
</properties>
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring.boot.dependency.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.dependency.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
    </dependencies>
</dependencyManagement>

 

 

 

我们在order-service服务的pom文件中引入feign的依赖:

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

2)添加注解

在order-service的启动类添加注解开启Feign的功能:@EnableFeignClients   

3)编写Feign的客户端

在order-service中新建一个接口,内容如下:

package cn.itcast.order.client;

import cn.itcast.order.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient("user-service")
public interface UserClient {
    @GetMapping("/user/{id}")
    User findById(@PathVariable("id") Long id);
}

这个客户端主要是基于SpringMVC的注解来声明远程调用的信息,比如:

  • 服务名称:userservice

  • 请求方式:GET

  • 请求路径:/user/{id}

  • 请求参数:Long id

  • 返回值类型:User

这样,Feign就可以帮助我们发送http请求,无需自己使用 RestTemplate 来发送了。

4)测试

修改order-service中的OrderService类中的queryOrderById方法,使用Feign客户端代替 RestTemplate:

 是不是看起来优雅多了。

5)总结

使用Feign的步骤:

① 引入依赖

② 添加@EnableFeignClients注解

③ 编写FeignClient接口,需要加 @FeignClient("user-service") 注解 ,里面的 user-service 为要调用服务的应用名称

④ 使用FeignClient中定义的方法代替 RestTemplate

2、自定义配置

Feign可以支持很多的自定义配置,如下表所示:

类型作用说明
feign.Logger.Level 修改日志级别 包含四种不同的级别:NONE、BASIC、HEADERS、FULL
feign.codec.Decoder 响应结果的解析器 http远程调用的结果做解析,例如解析json字符串为java对象
feign.codec.Encoder 请求参数编码 将请求参数编码,便于通过http请求发送
feign. Contract 支持的注解格式 默认是SpringMVC的注解
feign. Retryer 失败重试机制 请求失败的重试机制,默认是没有,不过会使用Ribbon的重试

一般情况下,默认值就能满足我们使用,如果要自定义时,只需要创建自定义的@Bean覆盖默认Bean即可。

 

下面以日志为例来演示如何自定义配置。

1)、配置文件方式

基于配置文件修改feign的日志级别可以针对单个服务:

feign:  
  client:
    config: 
      user-service: # 针对某个微服务的配置
        loggerLevel: FULL #  日志级别 

也可以针对所有服务:

feign:  
  client:
    config: 
      default: # 这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置
        loggerLevel: FULL #  日志级别 

而日志的级别分为四种:

  • NONE:不记录任何日志信息,这是默认值。  ------(推荐使用)

  • BASIC:仅记录请求的方法,URL以及响应状态码和执行时间 ------(推荐使用)

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

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

2)、Java代码方式

也可以基于Java代码来修改日志级别,先声明一个类,然后声明一个Logger.Level的对象:

public class DefaultFeignConfiguration  {
    @Bean
    public Logger.Level feignLogLevel(){
        return Logger.Level.BASIC; // 日志级别为BASIC
    }
}

 

如果要全局生效,将其放到启动类的@EnableFeignClients这个注解中:

@SpringBootApplication
@EnableFeignClients(clients = {UserClient.class}, defaultConfiguration = FeignClientLog.class)
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}

 

如果是局部生效,则把它放到接口对应的 @FeignClient 这个注解中

@Component
@FeignClient(value = "user-service", configuration = FeignClientLog.class)
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}

3、Feign使用优化

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

•URLConnection:默认实现,不支持连接池,性能差

•Apache HttpClient :支持连接池

•OKHttp:支持连接池

 

因此提高Feign的性能主要手段就是使用连接池代替默认的URLConnection。

 

这里我们用Apache的HttpClient来演示。

1)引入依赖

在order-service的pom文件中引入Apache的HttpClient依赖:

<!--httpClient的依赖 -->
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
</dependency>

2)配置连接池

在order-service的application.yml中添加配置:

feign:
  client:
    config:
      default: # default全局的配置
        loggerLevel: BASIC # 日志级别,BASIC就是基本的请求和响应信息
  httpclient:
    enabled: true # 开启feign对HttpClient的支持
    max-connections: 200 # 最大的连接数
    max-connections-per-route: 50 # 每个路径的最大连接数

接下来,在FeignClientFactoryBean中的loadBalance方法中打断点:

 Debug方式启动order-service服务,可以看到这里的client,底层就是Apache HttpClient:

总结,Feign的优化:

1.日志级别尽量用basic

2.使用HttpClient或OKHttp代替URLConnection

① 引入feign-httpClient依赖

② 配置文件开启httpClient功能,设置连接池参数

4、最佳实践

所谓最近实践,就是使用过程中总结的经验,最好的一种使用方式。

自习观察可以发现,Feign的客户端与服务提供者的controller代码非常相似:

feign客户端:

 UserController:

 有没有一种办法简化这种重复的代码编写呢?

1、继承方式

一样的代码可以通过继承来共享:

1)定义一个API接口,利用定义方法,并基于SpringMVC注解做声明。

2)Feign客户端和Controller都集成该接口

优点:

  • 简单

  • 实现了代码共享

缺点:

  • 服务提供方、服务消费方紧耦合

  • 参数列表中的注解映射并不会继承,因此Controller中必须再次声明方法、参数列表、注解

2、抽取方式

将Feign的Client抽取为独立模块,并且把接口有关的POJO、默认的Feign配置都放到这个模块中,提供给所有消费者使用。

例如,将UserClient、User、Feign的默认配置都抽取到一个feign-api包中,所有微服务引用该依赖包,即可直接使用。

3、实现基于抽取的最佳实践

1)、抽取

首先创建一个module,命名为feign-api:

 项目结构:

 在feign-api中然后引入feign的starter依赖

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

然后,order-service中编写的UserClient、User、DefaultFeignConfiguration都复制到feign-api项目中

2)在order-service中使用feign-api

首先,删除order-service中的UserClient、User、DefaultFeignConfiguration等类或接口。

在order-service的pom文件中中引入feign-api的依赖:

<dependency>
    <groupId>cn.itcast.demo</groupId>
    <artifactId>feign-api</artifactId>
    <version>1.0</version>
</dependency>

修改order-service中的所有与上述三个组件有关的导包部分,改成导入feign-api中的包

 

3)重启测试

重启后,发现服务报错了:

这是因为  UserClient  现在在  cn.itcast.client 包下,

而 order-service 的  @EnableFeignClients  注解是在 cn.itcast.order 包下,不在同一个包,无法扫描到 UserClient。

4)解决扫描包问题

方式一:

指定Feign应该扫描的包:

@SpringBootApplication
@EnableFeignClients(basePackages = "cn.itcast.client")
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}

方式二:

指定需要加载的Client接口:

package cn.itcast.order;

import cn.itcast.client.UserClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.openfeign.EnableFeignClients;


@SpringBootApplication
@EnableFeignClients(clients = {UserClient.class})
public class OrderApplication {

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

}

重启服务,请求接口,浏览器正常显示结果

 

5、Feign远程调服务中调用,传递 token

默认spring-boot 微服务中 用 Feign来做服务间调用,是不会携带 token传递的。为了能让服务间调用的时候带上token, 需要进行配置,增强 Feign

1、在feign-api 服务中创建  FeignConfiguration.java  配置类

package cn.itcast.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration
public class FeignConfiguration implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("authorization"); // authorization 替换为自己的请求头名称,下同
        if(attributes == null || (request == null)){
            log.info("--请求中未携带authorization.......");
            return;
        }
        requestTemplate.header("authorization", token);
    }
}

 

2、在 @FeignClient 接口中添加  configuration = FeignConfiguration.class

package cn.itcast.client;

import cn.itcast.config.FeignConfiguration;
import cn.itcast.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Component
@FeignClient(value = "gateway", configuration = FeignConfiguration.class)
public interface UserClient {
    @GetMapping("/user/{id}")
    User findById(@PathVariable("id") Long id);
}
 
完成上述步骤,重启服务后,可以远程调用成功
 
 
由于 Feign的 熔断器hystrix的隔离策略的原因,feign调用线程和主线程隔离了,请求上下文不共用,导致feign拦截器中 RequestContextHolder.getRequestAttributes()为空
 
原因:
此属性指示HystrixCommand.run()执行哪种隔离策略,是以下两种选择之一:
  • THREAD —它在单独的线程上执行,并发请求受线程池中线程数的限制
  • SEMAPHORE —它在调用线程上执行,并发请求受信号量限制

 

 

自定义feign的并发策略 继承HystrixConcurrencyStrategy,然后重写wrapCallable方法。如下:

import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


import java.util.concurrent.Callable;

/**
 * Created by YangGuanRong
 * date: 2022/3/8
 */
@Slf4j
@Primary
@Component
public class CustomFeignHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {

    public CustomFeignHystrixConcurrencyStrategy() {
        try {

            HystrixPlugins.getInstance().registerConcurrencyStrategy(this);

        } catch (Exception e) {
            log.error("Failed to register Sleuth Hystrix Concurrency Strategy", e);
        }
    }


    @Override
    public <T> Callable<T> wrapCallable(Callable<T> callable) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return new WrappedCallable<>(callable, requestAttributes);
    }


    static class WrappedCallable<T> implements Callable<T> {
        private final Callable<T> target;
        private final RequestAttributes requestAttributes;

        public WrappedCallable(Callable<T> target, RequestAttributes requestAttributes) {
            this.target = target;
            this.requestAttributes = requestAttributes;
        }

        /**
         * feign opens the fuse (hystrix): feign.hystrix.enabled=ture, and uses the default signal isolation level,
         * The HttpServletRequest object is independent of each other in the parent thread and the child thread and is not shared.
         * So the HttpServletRequest data of the parent thread used in the child thread is null,
         * naturally it is impossible to obtain the token information of the request header In a multithreaded environment, call before the request, set the context before the call
         *
         * feign启用了hystrix,并且feign.hystrix.enabled=ture。采用了线程隔离策略。
         * HttpServletRequest 请求在对象在父线程和子线程中相互独立,且不共享
         * 所以父线程的 HttpServletRequest 在子线程中为空,
         * 所以通常 在多线程环境中,在请求调用之前设置上下文
         * @return T
         * @throws Exception Exception
         */
        @Override
        public T call() throws Exception {
            try {
                // Set true to share the parent thread's HttpServletRequest object setting
                RequestContextHolder.setRequestAttributes(requestAttributes, true);
                return target.call();
            } finally {
                RequestContextHolder.resetRequestAttributes();
            }
        }
    }
}

 

posted @ 2022-12-08 12:11  DeyouKong  阅读(191)  评论(0编辑  收藏  举报