原生Feign使用详解(HTTP客户端)(二)

简介: 原生Feign使用详解(HTTP客户端)(二)

原生Feign使用详解(HTTP客户端)(一):

六,高级用法

6.1,Base APIS

有些请求中的一些方法是通用的,但是可能会有不同的参数类型或者返回类型,这个时候可以这么用:

// 通用API
interface BaseAPI {
 @RequestLine("GET /health")
 String health();
 @RequestLine("GET /all")
 List<Entity> all();
}
// 继承通用API
interface CustomAPI extends BaseAPI {
 @RequestLine("GET /custom")
 String custom();
}
// 各种类型有相同的表现形式,定义一个统一的API
@Headers("Accept: application/json")
interface BaseApi<V> {
 @RequestLine("GET /api/{key}")
 V get(@Param("key") String key);
 @RequestLine("GET /api")
 List<V> list();
 @Headers("Content-Type: application/json")
 @RequestLine("PUT /api/{key}")
 void put(@Param("key") String key, V value);
}
// 根据不同的类型来继承
interface FooApi extends BaseApi<Foo> { }
interface BarApi extends BaseApi<Bar> { }

6.2,Logging

你可以通过设置一个 Logger 来记录http消息,如下:

GitHub github = Feign.builder()
           .decoder(new GsonDecoder())
           .logger(new Logger.JavaLogger().appendToFile("logs/http.log"))
           .logLevel(Logger.Level.FULL)
           .target(GitHub.class, https://api.github.com);

也可以参考上面的 SLF4J 章节的说明

6.3,Request Interceptors

当你希望修改所有的的请求的时候,你可以使用Request Interceptors。比如说,你作为一个中介,你可能需要为每个请求设置 X-Forwarded-For

static class ForwardedForInterceptor implements RequestInterceptor {
 @Override public void apply(RequestTemplate template) {
  template.header("X-Forwarded-For", "origin.host.com");
 }
}
...
Bank bank = Feign.builder()
         .decoder(accountDecoder)
         .requestInterceptor(new ForwardedForInterceptor())
         .target(Bank.class, https://api.examplebank.com);

或者,你可能需要实现Basic Auth,这里有一个内置的基础校验拦截器

BasicAuthRequestInterceptor
Bank bank = Feign.builder()
         .decoder(accountDecoder)
         .requestInterceptor(new BasicAuthRequestInterceptor(username, password))
         .target(Bank.class, https://api.examplebank.com);

6.4,Custom @Param Expansion

在使用 @Param 注解给模板中的参数设值的时候,默认的是使用的对象的 toString() 方法的值,通过声明 自定义的Param.Expander,用户可以控制其行为,比如说格式化 Date 类型的值:

// 通过设置 @Param 的 expander 为 DateToMillis.class 可以定义Date类型的值
@RequestLine("GET /?since={date}")
Result list(@Param(value = "date", expander = DateToMillis.class) Date date);

6.5,Dynamic Query Parameters

动态查询参数支持,通过使用 @QueryMap 可以允许动态传入请求参数,如下:

@RequestLine("GET /find")
V find(@QueryMap Map<String, Object> queryMap);

6.6,Static and Default Methods

如果你使用的是JDK 1.8+ 的话,那么你可以给接口设置统一的默认方法和静态方法,这个事JDK8的新特性,如下:

interface GitHub {
@RequestLine("GET /repos/{owner}/{repo}/contributors")
 List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
 @RequestLine("GET /users/{username}/repos?sort={sort}")
 List<Repo> repos(@Param("username") String owner, @Param("sort") String sort);
 default List<Repo> repos(String owner) {
  return repos(owner, "full_name");
 }
 /**
  * Lists all contributors for all repos owned by a user.
  */
 default List<Contributor> contributors(String user) {
  MergingContributorList contributors = new MergingContributorList();
  for(Repo repo : this.repos(owner)) {
   contributors.addAll(this.contributors(user, repo.getName()));
  }
  return contributors.mergeResult();
 }
 static GitHub connect() {
  return Feign.builder()
        .decoder(new GsonDecoder())
        .target(GitHub.class, "https://api.github.com");
 }
}

参考自:https://github.com/OpenFeign/feign

目录
相关文章
|
6月前
|
JSON 中间件 Go
Go 网络编程:HTTP服务与客户端开发
Go 语言的 `net/http` 包功能强大,可快速构建高并发 HTTP 服务。本文从创建简单 HTTP 服务入手,逐步讲解请求与响应对象、URL 参数处理、自定义路由、JSON 接口、静态文件服务、中间件编写及 HTTPS 配置等内容。通过示例代码展示如何使用 `http.HandleFunc`、`http.ServeMux`、`http.Client` 等工具实现常见功能,帮助开发者掌握构建高效 Web 应用的核心技能。
343 61
|
4月前
|
数据采集 JSON Go
Go语言实战案例:实现HTTP客户端请求并解析响应
本文是 Go 网络与并发实战系列的第 2 篇,详细介绍如何使用 Go 构建 HTTP 客户端,涵盖请求发送、响应解析、错误处理、Header 与 Body 提取等流程,并通过实战代码演示如何并发请求多个 URL,适合希望掌握 Go 网络编程基础的开发者。
|
9月前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
851 29
使用Netty实现文件传输的HTTP服务器和客户端
本文通过详细的代码示例,展示了如何使用Netty框架实现一个文件传输的HTTP服务器和客户端,包括服务端的文件处理和客户端的文件请求与接收。
310 1
使用Netty实现文件传输的HTTP服务器和客户端
|
开发者 Python
深入解析Python `httpx`源码,探索现代HTTP客户端的秘密!
深入解析Python `httpx`源码,探索现代HTTP客户端的秘密!
330 1
|
Web App开发 前端开发 Android开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
使用MAT分析内存泄露 对于大型服务端应用程序来说,有些内存泄露问题很难在测试阶段发现,此时就需要分析JVM Heap Dump文件来找出问题。
926 0
|
Web App开发 监控 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
系统的升级涉及各个架构组件,细节很多。常年累月的修修补补使老系统积累了很多问题。 系统升级则意味着需要repair之前埋下的雷,那为何还要升级,可以考虑以下几个方面 成熟老系统常见问题: 1. 缺乏文档(这应该是大小公司都存在的问题。
707 0
|
Web App开发 前端开发
|
Web App开发 前端开发 Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
java链接MongoDB处理大量数据时经常碰到cursor not found 的异常,其实是超时所致 Exception in thread "main" com.
931 0
|
Web App开发 大数据
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
                                                                               1.
1856 0