你们都知道
okhttp
是一款由square公司开源的java
版本http
客户端工具。实际上,square公司还开源了基于okhttp
进一步封装的retrofit工具,用来支持经过接口
的方式发起http
请求。若是你的项目中还在直接使用RestTemplate
或者okhttp
,或者基于它们封装的HttpUtils
,那么你能够尝试使用Retrofit
。java
retrofit-spring-boot-starter实现了Retrofit
与spring-boot
框架快速整合,而且支持了部分功能加强,从而极大的简化spring-boot
项目下http
接口调用开发。接下来咱们直接经过retrofit-spring-boot-starter
,来看看spring-boot
项目发送http
请求有多简单。git
retrofit
官方并无提供与spring-boot
快速整合的starter
。retrofit-spring-boot-starter是笔者封装的,已在生产环境使用,很是稳定。造轮子不易,跪求各位大佬star。github
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
复制代码
@RetrofitScan
注解你能够给带有 @Configuration
的类配置@RetrofitScan
,或者直接配置到spring-boot
的启动类上,以下:spring
@SpringBootApplication
@RetrofitScan("com.github.lianjiatech.retrofit.spring.boot.test")
public class RetrofitTestApplication {
public static void main(String[] args) {
SpringApplication.run(RetrofitTestApplication.class, args);
}
}
复制代码
接口必须使用@RetrofitClient
注解标记!http相关注解可参考官方文档:retrofit官方文档。api
@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
}
复制代码
将接口注入到其它Service中便可使用。mybatis
@Service
public class TestService {
@Autowired
private HttpApi httpApi;
public void test() {
// 经过httpApi发起http请求
}
}
复制代码
只要经过上述几个步骤,就能实现经过接口发送http
请求了,真的很简单。若是你在spring-boot
项目里面使用过mybatis
,相信你对这种使用方式会更加熟悉。接下来咱们继续介绍一下retrofit-spring-boot-starter
更高级一点的功能。框架
不少时候,咱们但愿某个接口下的某些http请求执行统一的拦截处理逻辑。这个时候可使用注解式拦截器。使用的步骤主要分为2步:ide
BasePathMatchInterceptor
编写拦截处理器;@Intercept
进行标注。下面以给指定请求的url后面拼接timestamp时间戳为例,介绍下如何使用注解式拦截器。spring-boot
BasePathMatchInterceptor
编写拦截处理器@Component
public class TimeStampInterceptor extends BasePathMatchInterceptor {
@Override
public Response doIntercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl url = request.url();
long timestamp = System.currentTimeMillis();
HttpUrl newUrl = url.newBuilder()
.addQueryParameter("timestamp", String.valueOf(timestamp))
.build();
Request newRequest = request.newBuilder()
.url(newUrl)
.build();
return chain.proceed(newRequest);
}
}
复制代码
@Intercept
进行标注@RetrofitClient(baseUrl = "${test.baseUrl}")
@Intercept(handler = TimeStampInterceptor.class, include = {"/api/**"}, exclude = "/api/test/savePerson")
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
@POST("savePerson")
Result<Person> savePerson(@Body Person person);
}
复制代码
上面的@Intercept
配置表示:拦截HttpApi
接口下/api/**
路径下(排除/api/test/savePerson
)的请求,拦截处理器使用TimeStampInterceptor
。工具
有的时候,咱们须要在拦截注解动态传入一些参数,而后再执行拦截的时候须要使用这个参数。这种时候,咱们能够扩展实现自定义拦截注解。自定义拦截注解
必须使用@InterceptMark
标记,而且注解中必须包括include()、exclude()、handler()
属性信息。使用的步骤主要分为3步:
BasePathMatchInterceptor
编写拦截处理器例如咱们须要在请求头里面动态加入accessKeyId
、accessKeySecret
签名信息才能正常发起http请求,这个时候能够**自定义一个加签拦截器注解@Sign
**来实现。下面以自定义@Sign
拦截注解为例进行说明。
@Sign
注解@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@InterceptMark
public @interface Sign {
/** * 密钥key * 支持占位符形式配置。 * * @return */
String accessKeyId();
/** * 密钥 * 支持占位符形式配置。 * * @return */
String accessKeySecret();
/** * 拦截器匹配路径 * * @return */
String[] include() default {"/**"};
/** * 拦截器排除匹配,排除指定路径拦截 * * @return */
String[] exclude() default {};
/** * 处理该注解的拦截器类 * 优先从spring容器获取对应的Bean,若是获取不到,则使用反射建立一个! * * @return */
Class<? extends BasePathMatchInterceptor> handler() default SignInterceptor.class;
}
复制代码
扩展自定义拦截注解
有如下2点须要注意:
自定义拦截注解
必须使用@InterceptMark
标记。include()、exclude()、handler()
属性信息。SignInterceptor
@Component
public class SignInterceptor extends BasePathMatchInterceptor {
private String accessKeyId;
private String accessKeySecret;
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
@Override
public Response doIntercept(Chain chain) throws IOException {
Request request = chain.request();
Request newReq = request.newBuilder()
.addHeader("accessKeyId", accessKeyId)
.addHeader("accessKeySecret", accessKeySecret)
.build();
return chain.proceed(newReq);
}
}
复制代码
上述accessKeyId
和accessKeySecret
字段值会依据@Sign
注解的accessKeyId()
和accessKeySecret()
值自动注入,若是@Sign
指定的是占位符形式的字符串,则会取配置属性值进行注入。另外,accessKeyId
和accessKeySecret
字段必须提供setter
方法。
@Sign
@RetrofitClient(baseUrl = "${test.baseUrl}")
@Sign(accessKeyId = "${test.accessKeyId}", accessKeySecret = "${test.accessKeySecret}", exclude = {"/api/test/person"})
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
@POST("savePerson")
Result<Person> savePerson(@Body Person person);
}
复制代码
这样就能在指定url的请求上,自动加上签名信息了。
默认状况下,全部经过Retrofit
发送的http请求都会使用max-idle-connections=5 keep-alive-second=300
的默认链接池。固然,咱们也能够在配置文件中配置多个自定义的链接池,而后经过@RetrofitClient
的poolName
属性来指定使用。好比咱们要让某个接口下的请求所有使用poolName=test1
的链接池,代码实现以下:
配置链接池。
retrofit:
# 链接池配置
pool:
test1:
max-idle-connections: 3
keep-alive-second: 100
test2:
max-idle-connections: 5
keep-alive-second: 50
复制代码
经过@RetrofitClient
的poolName
属性来指定使用的链接池。
@RetrofitClient(baseUrl = "${test.baseUrl}", poolName="test1")
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
}
复制代码
不少状况下,咱们但愿将http请求日志记录下来。经过@RetrofitClient
的logLevel
和logStrategy
属性,您能够指定每一个接口的日志打印级别以及日志打印策略。retrofit-spring-boot-starter
支持了5种日志打印级别(ERROR
, WARN
, INFO
, DEBUG
, TRACE
),默认INFO
;支持了4种日志打印策略(NONE
, BASIC
, HEADERS
, BODY
),默认BASIC
。4种日志打印策略含义以下:
NONE
:No logs.BASIC
:Logs request and response lines.HEADERS
:Logs request and response lines and their respective headers.BODY
:Logs request and response lines and their respective headers and bodies (if present).retrofit-spring-boot-starter
默认使用了DefaultLoggingInterceptor
执行真正的日志打印功能,其底层就是okhttp
原生的HttpLoggingInterceptor
。固然,你也能够自定义实现本身的日志打印拦截器,只须要继承BaseLoggingInterceptor
(具体能够参考DefaultLoggingInterceptor
的实现),而后在配置文件中进行相关配置便可。
retrofit:
# 日志打印拦截器
logging-interceptor: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor
复制代码
当出现http请求异常时,原始的异常信息可能阅读起来并不友好,所以retrofit-spring-boot-starter
提供了Http异常信息格式化器
,用来美化输出http请求参数,默认使用DefaultHttpExceptionMessageFormatter
进行请求数据格式化。你也能够进行自定义,只须要继承BaseHttpExceptionMessageFormatter
,再进行相关配置便可。
retrofit:
# Http异常信息格式化器
http-exception-message-formatter: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultHttpExceptionMessageFormatter
复制代码
Retrofit
能够经过调用适配器CallAdapterFactory
将Call<T>
对象适配成接口方法的返回值类型。retrofit-spring-boot-starter
扩展2种CallAdapterFactory
实现:
BodyCallAdapterFactory
retrofit.enable-body-call-adapter=false
关闭Retrofit.Call<T>
、Retrofit.Response<T>
、java.util.concurrent.CompletableFuture<T>
以外,其它返回类型均可以使用该适配器。ResponseCallAdapterFactory
retrofit.enable-response-call-adapter=false
关闭Retrofit.Response<T>
返回。Retrofit.Response<T>
,则可使用该适配器。Retrofit自动根据方法返回值类型选用对应的CallAdapterFactory
执行适配处理!加上Retrofit默认的CallAdapterFactory
,可支持多种形式的方法返回值类型:
Call<T>
: 不执行适配处理,直接返回Call<T>
对象CompletableFuture<T>
: 将响应体内容适配成CompletableFuture<T>
对象返回Void
: 不关注返回类型可使用Void
。若是http状态码不是2xx,直接抛错!Response<T>
: 将响应内容适配成Response<T>
对象返回/** * Call<T> * 不执行适配处理,直接返回Call<T>对象 * @param id * @return */
@GET("person")
Call<Result<Person>> getPersonCall(@Query("id") Long id);
/** * CompletableFuture<T> * 将响应体内容适配成CompletableFuture<T>对象返回 * @param id * @return */
@GET("person")
CompletableFuture<Result<Person>> getPersonCompletableFuture(@Query("id") Long id);
/** * Void * 不关注返回类型可使用Void。若是http状态码不是2xx,直接抛错! * @param id * @return */
@GET("person")
Void getPersonVoid(@Query("id") Long id);
/** * Response<T> * 将响应内容适配成Response<T>对象返回 * @param id * @return */
@GET("person")
Response<Result<Person>> getPersonResponse(@Query("id") Long id);
/** * 其余任意Java类型 * 将响应体内容适配成一个对应的Java类型对象返回,若是http状态码不是2xx,直接抛错! * @param id * @return */
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
复制代码
咱们也能够经过继承CallAdapter.Factory
扩展实现本身的CallAdapter
;而后将自定义的CallAdapterFactory
配置成spring
的bean
!
自定义配置的
CallAdapter.Factory
优先级更高!
Retrofi
使用Converter
将@Body
注解标注的对象转换成请求体,将响应体数据转换成一个Java
对象,能够选用如下几种Converter
:
retrofit-spring-boot-starter
默认使用的是jackson进行序列化转换!若是须要使用其它序列化方式,在项目中引入对应的依赖,再把对应的ConverterFactory
配置成spring的bean便可。
咱们也能够经过继承Converter.Factory
扩展实现本身的Converter
;而后将自定义的Converter.Factory
配置成spring
的bean
!
自定义配置的
Converter.Factory
优先级更高!
若是咱们须要对整个系统的的http请求执行统一的拦截处理,能够自定义实现全局拦截器BaseGlobalInterceptor
, 并配置成spring
中的bean
!例如咱们须要在整个系统发起的http请求,都带上来源信息。
@Component
public class SourceInterceptor extends BaseGlobalInterceptor {
@Override
public Response doIntercept(Chain chain) throws IOException {
Request request = chain.request();
Request newReq = request.newBuilder()
.addHeader("source", "test")
.build();
return chain.proceed(newReq);
}
}
复制代码
至此,spring-boot项目下最优雅的http客户端工具介绍就结束了,更多详细信息能够参考官方文档:retrofit以及retrofit-spring-boot-starter。