微服务调用组件Feign

Java项目中如何实现接口调用

1》Httpclient
Httpclient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持Http协议的客户端编程工具包,并且它支持HTTP协议最新版本和建议。HttpClient相比传统JDK自带的URLConnection,提升了易用性和灵活性,使客户端发送HTTP请求变得容易,提高了开发的效率。
2》Okhttp
一个处理网络请求的开源项目,是安卓端最火的轻量级框架,由Square公司贡献,用于替代HttpUrlConnection和Apache HttpClient。OkHttp拥有简洁的API、高效的性能,并支持多种协议(HTTP/2和SPDY)。
3》HttpURLConnection
HttpURLConnection是Java的标准类,它继承自URLConnection,可用于向指定网站发送GET请求、POST请求、HttpURLConnection使用比较复杂,不像HttpClient那样容易使用。
4》RestTemplate WebClient
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程HTTP服务的方法,能够大大提高客户端的编写效率。

上面介绍的是最常见的几种调用接口的方法,我们下面要介绍的方法比上面的更简单、方便,它就是Feign。

什么是Feign

Feign是Netflix开发的声明式、模板化的HTTP客户端,其灵感来自Retrofit、JAXRS-2.0以及WebSocket。Feign可帮助我们更加便捷、优雅地调用HTTP API。
Feign支持多种注解,例如Fegin自带的注解或者JAX-RS注解等。

Spring Cloud openfeign对Feign进行了增强,使其支持Spring MVC注解,另外还整合了Ribbon和Nacos,从而使得Feign的使用更加方便。

优势:Feign可以做到使用HTTP请求远程服务时就像调用本地方法一样的体验,开发者完全感知不到这是远程方法,更感知不到这是个HTTP请求。它像Dubbo一样,consumer直接调用接口方法调用provider,而不需要通过常规的Http Client构造请求再解析返回数据,它解决了让开发者调用远程接口就像调用本地方法一样,无需关注与远程的交互细节,更无需关注分布式环境开发。

Spring Cloud Alibaba快速整合OpenFeign

1.引入依赖

<!--1.添加openfeign依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2.编写调用接口 + @FeignClient注解

/**
 * 2.添加feign接口和方法
 * name  指定调用rest接口所对应的服务名
 * path  指定调用rest接口所在的StockController指定的@
 */
@FeignClient(name = "stock-service", path = "/stock")
public interface StockFeignService {
    
    

    /**
     * 声明需要调用的rest接口对应的方法
     * @return
     */
    @RequestMapping("/reduct")
    String reduct();

}

3.调用端在启动类上添加@EnableFeignClients注解, 此注解高版本不用加。

@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
    
    

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

}

4.发起调用,像调用本地方法一样调用远程服务

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    
    

    @Autowired
    StockFeignService stockFeignService;

    @RequestMapping("/add")
    public String add(){
    
    
        log.info("下单成功!");
        String result = stockFeignService.reduct();
        return "Hello Feign !" + result;
    }
}

Spring Cloud Alibaba的自定义配置及使用

Feign提供了很多的扩展机制,让用户可以更加灵活的使用。

1.日志配置
有时候我们遇到Bug,比如接口调用失败,参数没收到等问题,或者想看看调用性能,就需要配置Feign的日志了,以此让Feign把请求信息输出来。

1》定义一个配置类,指定日志级别

/**
 * 注意:此处配置@Configuration注解就会全局生效,如果想指定对应微服务生效,就不能配置
 */
@Configuration
public class FeignConfig {
    
    

    @Bean
    public Logger.Level feignLoggerLevel(){
    
    
        return Logger.Level.FULL;
    }
}

通过源码可以看到日志等级有4种,分别是:
(1) NONE【性能最佳,适用于生产】:不记录任何日志(默认值)。
(2) BASIC【适用于生产环境追踪问题】:仅记录请求方法,URL、响应状态代码以及执行时间。
(3) HEADERS:记录BASIC级别的基础上,记录请求和响应的header。
(4) FULL【比较适用于开发及测试环境定位问题】:记录请求和响应的header、body和元数据。

2》在yml配置文件中执行Client的日志级别才能正常输出日志,格式是"logging.level.feign接口包路径=debug"

#Springboot默认的日志级别是info,feign的debug日志级别就不会输入
logging:
  level:
    com.mu.order.feign: debug

3》局部配置,让调用的微服务生效,在@FeignClient注解中指定使用的配置类

@FeignClient(name = "product-service", path = "/product", configuration = FeignConfig.class)
public interface ProductFeignService {
    
    

    @RequestMapping("/{id}")
    String get(@PathVariable("id") Integer id);
}

4》局部配置可以在yml中配置

# feign日志局部配置
feign:
  client:
    config:
      stock-service:
        loggerLevel: BASIC

在这里插入图片描述
2.契约配置
Spring Cloud在Feign的基础上做了扩展,使用Spring MVC的注解来完成Feign的功能。原生的Feign是不支持Spring MVC注解的,如果你想在Spring Cloud中使用原生的注解方式来定义客户端也是可以的,通过配置契约来改变这个配置,Spring Cloud中默认的是SpringMVCContract。

Spring Cloud 1 早期版本就是用的原生Fegin,随着Netflix的停更替换成了Openfeign。

1》修改契约配置,支持Feign原生的注解

/**
* 修改契约配置,支持Feign原生的注解
* @return
*/
@Bean
public Contract feignContract(){
    
    
	return new Contract.Default();
}

注意:修改契约配置后,ProductFeignService 不再支持springmvc的注解,需要使用Fegin原生注解

2》ProductFeignService 中配置使用Feign原生的注解

@FeignClient(name = "product-service", path = "/product")
public interface ProductFeignService {
    
    

    /*@RequestMapping("/{id}")
    String get(@PathVariable("id") Integer id);*/

    @RequestLine("GET /{id}")
    String get(@Param("id") Integer id);
}

3》补充,也可以通过yml配置契约

# feign日志局部配置
feign:
  client:
    config:
      product-service:
        loggerLevel: BASIC
        contract: feign.Contract.Default # 设置为默认值的契约(还原成原注解)

3.超时时间配置
通过Options可以配置连接超时时间和读取超时时间,Options的第一个参数是连接的超时时间(ms),默认值是2s; 第二个是请求处理的超时时间(ms),默认值是5s。

全局配置:

@Configuration
public class FeignConfig{
    
    
	@Bean
	public Request.Options options(){
    
    
		return new Request.Options(5000,10000);
	}
}

yml中配置:

# feign日志局部配置
feign:
  client:
    config:
      product-service:
        loggerLevel: BASIC
        contract: feign.Contract.Default # 设置为默认值的契约(还原成原注解)
        # 连接超时时间,默认2s
        connectTimeout: 5000
        # 请求处理超时时间,默认5s
        readTimeout: 3000

补充说明:Feign的底层用的是Ribbon,但是超时时间以Feign配置为准。

测试超时情况:
在这里插入图片描述

4.自定义拦截器实现认证逻辑

public class CustomFeignInterceptor implements RequestInterceptor {
    
    

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void apply(RequestTemplate requestTemplate) {
    
    
        //TODO
        requestTemplate.header("xxx", "xxx");
        requestTemplate.query("id", "111");
        requestTemplate.uri("/9");

        logger.info("feign拦截器!");
    }
}

全局配置:

 /**
 * 自定义拦截器
 * @return
 */
public CustomFeignInterceptor customFeignInterceptor(){
    
    
    return new CustomFeignInterceptor();
}

可以在yml中配置:

# feign日志局部配置
feign:
  client:
    config:
      product-service:
        loggerLevel: BASIC
        contract: feign.Contract.Default # 设置为默认值的契约(还原成原注解)
        # 连接超时时间,默认2s
        connectTimeout: 5000
        # 请求处理超时时间,默认5s
        readTimeout: 10000
        requestInterceptors:
          - com.mu.order.interceptor.feign.CustomFeignInterceptor

测试:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/muriyue6/article/details/121261350