SpringCloudAlibaba - 整合 Feign 实现远程 HTTP 调用

前言

FeignNetflix开源的声明式HTTP客户端,致力于让编写http client更加简单,Feign可以通过声明接口自动构造请求的目标地址完成请求


环境

Spring Cloud Hoxton.SR9 + Spring Cloud Alibaba 2.2.6.RELEASE
FeignNetflix公司产品,目前已停止更新,文章中使用的是OpenFeign,是Spring社区开发的组件


简单示例

content-center

  • pom.xml
<!-- openfeign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  • 启动类ContentCenterApplication.java
@EnableFeignClients
public class ContentCenterApplication {
}
  • TestController.java
import com.coisini.contentcenter.feignclient.TestFeignClient;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestController {

     private final TestFeignClient testFeignClient;

	/**
     * 整合Feign
     * @return
     */
    @GetMapping("test4")
    public String test4() {
        return testFeignClient.test("Coisini");
    }
    
}
  • TestFeignClient.java
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @FeignClient(name = "user-center") 
 * name 要请求的微服务的名称
 */
@FeignClient(name = "user-center")
public interface TestFeignClient{

    /**
     * test接口被调用时,feign会构造出 url
     * http://user-center/test/{name} 完成请求
     * @param name
     * @return
     */
    @GetMapping("/test/{name}")
    String test(@PathVariable String name);

}

user-center

  • TestController.java
@RestController
@Slf4j
public class TestController {

    @GetMapping("/test/{name}")
    public String test(@PathVariable String name) {
        log.info("请求...");
        return "hello " + name;
    }

}

示例测试结果

在这里插入图片描述


…至此,已完成Feign的整合


Feign 的组成和支持的配置项

Feign 的组成

接口作用默认值
Feign.BuilderFeign的入口Feign.Builder
ClientFeign底层请求方式和Ribbon配合时 LoadBalancerFeignClient
不和Ribbon配合时 feign.Client.Default
Contract契约,注解支持SpringMvcContract
Encoder编码器,用于将对象转换成HTTP请求消息体SpringEncoder
Decoder解码器,将响应消息转换成对象ResponseEntityDecoder
Logger日志管理器Slf4jLogger
RequestInterceptor用于为每个请求添加通用逻辑

Feign 支持的配置项

代码配置支持的配置项

配置项作用
Logger.Level指定日志级别
Retryer指定重试策略
ErrorDecoder指定错误解码器
Request.Options超时时间
Collection< RequestInterceptor>拦截器
SetterFactory用于设置Hystrix的配置属性,整合Hystrix才会生效

配置属性支持的配置项

feign.client.config: 
  <feignName>:
    connectTimeout: 5000 # 连接超时时间
    readTimeout: 5000 # 读取超时时间
    loggerLevel: full # 日志级别
    errorDecoder: com.example.SimpleErrorDecoder # 错误解码器
    retryer: com.example.SimpleRetryer # 重试策略
    requestInterceptors: com.example.FooRequestInterceptor # 拦截器
    decode404: false # 是否对404错误码解码
    encoder: com.example.SimpleEncoder # 编码器
    decoder: com.example.SimpleDecoder # 解码器
    contract: com.example.SimpleContract # 契约

Feign 的日志

Feign 的日志级别

  • feign默认不打印任何日志
级别打印内容
NONE(默认值)不记录任何日志
BASIC仅记录请求方法、URL、响应状态代码以及执行时间
HEADERSBASIC级别的基础上,记录请求和响应的header
FULL记录请求和响应的header、body和元数据

自定义配置 Feign 的日志级别

Java 代码配置方式

  • UserCenterFeignConfiguration.java
import feign.Logger;
import org.springframework.context.annotation.Bean;

/**
 * @Description 用户中心 Feign 配置类
 */
public class UserCenterFeignConfiguration {

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

}
  • UserCenterFeignClient.java
@FeignClient(name = "user-center", configuration = UserCenterFeignConfiguration.class)
public interface UserCenterFeignClient {
	...
}
  • application.yml
logging:
  level:
    # feign 的日志级别是建立在接口日志级别基础上的
    com.coisini.contentcenter.feignclient.UserCenterFeignClient: debug
  • 访问接口查看feign日志

在这里插入图片描述


yml 属性配置方式

  • application.yml,实现效果同上
logging:
  level:
    com.coisini.contentcenter.feignclient.UserCenterFeignClient: debug

# 自定义配置 feign 日志级别
feign:
  client:
    config:
      # 调用的微服务名称
      user-center:
        loggerLevel: full

全局配置 Feign 的日志级别

Java 代码配置方式

  • GlobalFeignConfiguration.java
import feign.Logger;
import org.springframework.context.annotation.Bean;

/**
 * @Description Feign 全局配置类
 */
public class GlobalFeignConfiguration {

    @Bean
    public Logger.Level level() {
        // feign 日志级别 FULL
        return Logger.Level.FULL;
    }

}
  • 启动类ContentCenterApplication.java
@EnableFeignClients(defaultConfiguration = GlobalFeignConfiguration.class)
@SpringBootApplication
public class ContentCenterApplication {
	...
}
  • application.yml
logging:
  level:
    com.coisini.contentcenter.feignclient.UserCenterFeignClient: debug
  • 接口日志打印

在这里插入图片描述


yml 属性配置方式

  • application.yml
# 自定义配置 feign 日志级别
feign:
  client:
    config:
      # 全局配置
      default:
        loggerLevel: full
  • 实现效果同上

Feign 日志级别配置方式总结

  • 配置方式优先级:全局代码配置 < 全局属性配置 < 自定义代码配置(细粒度) < 自定义属性配置(细粒度)
  • 建议尽量使用属性配置

项目源码



- End -
- 个人学习笔记 -
- 仅供参考 -

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要使用Nacos整合Feign进行HTTPS远程调用,需要以下步骤: 1. 在Nacos中注册服务,并启用HTTPS协议。 2. 在Feign配置中添加HTTPS相关的配置,如下: ```java @Configuration public class FeignConfig { @Bean public Client feignClient() { return new OkHttpClient.Builder() .sslSocketFactory(createSSLSocketFactory()) .hostnameVerifier(createHostnameVerifier()) .build(); } private SSLSocketFactory createSSLSocketFactory() { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}, new SecureRandom()); return sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new RuntimeException(e); } } private HostnameVerifier createHostnameVerifier() { return (s, sslSession) -> true; } } ``` 3. 在Feign的接口上添加@FeignClient注解,并指定Nacos中注册的服务名和HTTPS协议,如下: ```java @FeignClient(name = "service-provider", url = "https://service-provider", configuration = FeignConfig.class) public interface ServiceProviderClient { @GetMapping("/hello") String sayHello(); } ``` 这样就可以使用Nacos整合Feign进行HTTPS远程调用了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Maggieq8324

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值