目录
介绍
retrofit-spring-boot-starter 是一个用于整合 Retrofit 库和 Spring Boot 的 starter 项目。使用它可以简化在 Spring Boot 中使用 Retrofit 的配置和使用。
简单使用
Spring Boot 3.x 项目,请使用retrofit-spring-boot-starter 3.x。 Spring Boot 1.x/2.x 项目,请使用retrofit-spring-boot-starter 2.x。以下示例基于2.x
依赖
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.3.12</version>
</dependency>
定义接口
@RetrofitClient(baseUrl = "${trilateral.baseUrl}")
public interface TrilateralApi {
/**
* 根据id获取用户信息
* @param id
* @return
*/
@GET("query/customer/view")
Response<Customer> getCustomer(@Query("id") Long id);
/**
* 保存用户信息
* @param customer
* @return 返回保存的信息
*/
@POST("query/customer/save")
Response<Customer> saveCustomer(@Body Customer customer);
}
注入
@RestController
@RequestMapping("/customer")
public class CustomerController {
@Autowired
private TrilateralApi trilateralApi;
@GetMapping("view")
@ResponseBody
public Customer view(@RequestParam(value = "id") Long id) {
Response<Customer> customer = trilateralApi.getCustomer(id);
return customer.body();
}
@PostMapping("save")
@ResponseBody
public Customer save(@RequestBody Customer customer) {
return trilateralApi.saveCustomer(customer).body();
}
}
配置文件
server:
port: 8007
retrofit:
# 全局转换器工厂
global-converter-factories:
- com.github.lianjiatech.retrofit.spring.boot.core.BasicTypeConverterFactory
- retrofit2.converter.jackson.JacksonConverterFactory
# 全局调用适配器工厂(组件扩展的调用适配器工厂已经内置,这里请勿重复配置)
global-call-adapter-factories:
# 全局日志打印配置
global-log:
# 启用日志打印
enable: true
# 全局日志打印级别
log-level: info
# 全局日志打印策略
log-strategy: basic
# 全局重试配置
global-retry:
# 是否启用全局重试
enable: false
# 全局重试间隔时间
interval-ms: 100
# 全局最大重试次数
max-retries: 2
# 全局重试规则
retry-rules:
- response_status_not_2xx
- occur_io_exception
# 全局超时时间配置
global-timeout:
# 全局读取超时时间
read-timeout-ms: 10000
# 全局写入超时时间
write-timeout-ms: 10000
# 全局连接超时时间
connect-timeout-ms: 10000
# 全局完整调用超时时间
call-timeout-ms: 0
# 熔断降级配置
degrade:
# 熔断降级类型。默认none,表示不启用熔断降级
degrade-type: none
#degrade-type: sentinel
# 全局sentinel降级配置
global-sentinel-degrade:
# 是否开启
enable: true
# 各降级策略对应的阈值。平均响应时间(ms),异常比例(0-1),异常数量(1-N)
count: 500
# 触发熔断后,熔断的时长,单位为 s
time-window: 5
# 降级策略(0:平均响应时间;1:异常比例;2:异常数量)
grade: 0
# 全局resilience4j降级配置
global-resilience4j-degrade:
# 是否开启
enable: false
# 根据该名称从#{@link CircuitBreakerConfigRegistry}获取CircuitBreakerConfig,作为全局熔断配置
circuit-breaker-config-name: defaultCircuitBreakerConfig
# 自动设置PathMathInterceptor的scope为prototype
auto-set-prototype-scope-for-path-math-interceptor: true
trilateral:
baseUrl: http://localhost:8027/
拦截器
局部拦截器, 继承BasePathMatchInterceptor , 例子:登录的token
/**
* @Description: 注解式拦截器
* 看登录状态是否过期,如过期,重启设置
*/
@Component
public class TokenInterceptor extends BasePathMatchInterceptor {
private volatile long expired;
private volatile String token;
private long tokenExpiredTime = 300000;
@Override
public Response doIntercept(Chain chain) throws IOException {
long now = System.currentTimeMillis();
Request request = chain.request();
HttpUrl url = request.url();
if (token == null || expired < now + tokenExpiredTime) {
synchronized (this) {
if (token == null || expired < now + tokenExpiredTime) {
refreshToken();
}
}
}
request = request.newBuilder()
.url(url)
.addHeader("token", token)
.build();
return chain.proceed(request);
}
/**
* 更新Token参数
*/
private void refreshToken() {
this.token = "newToken";
this.expired = System.currentTimeMillis() + (tokenExpiredTime * 2);
}
}
在API接口增加注解
/**
* Intercept配置表示:拦截TrilateralApi接口下/query/**路径下(排除/query/customer/view)的请求,拦截处理器使用TimeStampInterceptor。
* 需要多个拦截器往下追加即可
*/
@RetrofitClient(baseUrl = "${trilateral.baseUrl}")
@Intercept(handler = TokenInterceptor.class, include = {"/query/**"}, exclude = "/query/customer/view")
//@Intercept(handler = TokenInterceptor2.class, include = {"/query/**"}, exclude = "/query/customer/view")
public interface TrilateralApi {
全局拦截器:设置全局拦截器, 实现GlobalInterceptor
熔断降级
- 默认关闭状态, 配置文件开启熔断降低, 当前支持sentinel和resilience4j两种实现。
- 配置fallback或者fallbackFactory (可选) 如果@RetrofitClient不设置fallback或者fallbackFactory,当触发熔断时,会直接抛出RetrofitBlockException异常。 用户可以通过设置fallback或者fallbackFactory来定制熔断时的方法返回值。两者区别在于fallbackFactory可以看错误信息
- 依赖
<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-core</artifactId> <version>1.6.3</version> </dependency>
- fallback示例代码
/** * 实现定义的api接口 */ @Component public class TrilateralApiFallback implements TrilateralApi { @Override public Response<Customer> getCustomer(Long id) { return Response.success(new Customer()); } @Override public Response<Customer> saveCustomer(Customer customer) { return Response.success(new Customer()); } } //API接口增加fallback 属性 fallback类必须是当前接口的实现类, @RetrofitClient(baseUrl = "${trilateral.baseUrl}", fallback = TrilateralApiFallback.class) public interface TrilateralApi {
- fallbackFactory示例代码
/** * 实现定义的FallbackFactory接口,<T>需为定义的api接口 */ @Component public class TrilateralDegradeFallbackFactory implements FallbackFactory<TrilateralApi> { @Override public TrilateralApi create(Throwable cause) { System.out.println("触发熔断了!" + cause.getMessage() + " cause:" + cause); return new TrilateralApi() { @Override public Response<Customer> getCustomer(Long id) { return Response.success(new Customer()); } @Override public Response<Customer> saveCustomer(Customer customer) { return Response.success(new Customer()); } }; } } //API接口增加fallbackFactory 属性 @RetrofitClient(baseUrl = "${trilateral.baseUrl}", fallbackFactory = TrilateralDegradeFallbackFactory.class) public interface TrilateralApi {
retrofit-spring-boot-starter除此之外还支持自定义OkHttpClient,日志打印,请求重试,错误解码器,微服务之间的HTTP调用,调用适配器,数据转换器,元注解等, 更多功能使用详见:retrofit-spring-boot-starter: A spring-boot starter for retrofit, supports rapid integration and feature enhancements.(适用于retrofit的spring-boot启动器,支持快速集成和功能增强)