原生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

目录
相关文章
|
12天前
|
JSON 数据格式 Python
Python 的 requests 库是一个强大的 HTTP 客户端库,用于发送各种类型的 HTTP 请求
【6月更文挑战第15天】Python的requests库简化了HTTP请求。安装后,使用`requests.get()`发送GET请求,检查`status_code`为200表示成功。类似地,`requests.post()`用于POST请求,需提供JSON数据和`Content-Type`头。
36 6
|
1天前
|
数据采集 Java API
Java HTTP客户端工具的演变之路
Java HTTP客户端工具的演变之路
7 0
|
3天前
|
JSON API 数据格式
curl 使用:命令行中的 HTTP 客户端
`curl` 是命令行神器,用于与服务器交互,支持HTTP、HTTPS、FTP等协议。本文教你如何用它做POST请求(-d/--data)、GET请求(-G/-d)、JSON请求(-H &#39;Content-Type: application/json&#39;)和文件上传(-F)。学会这些,轻松测试API、自动化任务。现在就动手试试吧!
7 0
|
9天前
|
JSON 前端开发 JavaScript
Axios是一个基于Promise的HTTP客户端
Axios是一个基于Promise的HTTP客户端
13 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
最近在线上往hbase导数据,因为hbase写入能力比较强,没有太在意写的问题。让业务方进行历史数据的导入操作,中间发现一个问题,写入速度太快,并且业务数据集中到其中一个region,这个region无法split掉,处于不可用状态。
1312 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
Every Programmer Should Know These Latency Numbers 1秒=1000毫秒(ms) 1秒=1,000,000 微秒(μs) 1秒=1,000,000,000 纳秒(ns) 1秒=1,000,000,000,000 皮秒(ps) L1 cache reference .
625 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
hadoop服务器更换硬盘操作步骤(datanode hadoop目录${HADOOP_HOME}/bin    日志位置:/var/log/hadoop)1.登陆服务器,切换到mapred用户,执行jps命令,查看是否有TaskTracker进程。
989 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
从hadoop移除机器把需要移除的机器增加到exclueds文件中,强制刷新datanode列表,等待decommission 状态正常后,即可停机下架,如有必要在namenode执行balancer操作。
662 0
|
SQL 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
     如果在INSERT语句末尾指定了ON DUPLICATE KEY UPDATE,并且插入行后会导致在一个UNIQUE索引或PRIMARY KEY中出现重复值,则在出现重复值的行执行UPDATE;如果不会导致唯一值列重复的问题,则插入新行。
756 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
mysql修改表、字段、库的字符集 修改数据库字符集: ALTER DATABASE db_name DEFAULT CHARACTER SET character_name [COLLATE .
681 0