Skip to content

HTTP 客户端插件

声明式 HTTP 客户端,类似 Feign,简化外部 API 调用。

版本要求

该插件需要 LCGYL Framework Core v2.2.0 或更高版本。

功能特性

  • 声明式接口 - @HttpClient 定义客户端接口
  • 注解驱动 - @GET/@POST/@PUT/@DELETE 方法注解
  • 自动编解码 - 内置 Jackson JSON 编解码器
  • 请求拦截器 - 日志、追踪、认证
  • 超时重试 - 可配置超时和重试策略
  • Actuator 端点 - 客户端状态监控

快速开始

添加依赖

gradle
implementation 'com.lcgyl:lcgyl-http-client-plugin:2.2.0'

启用客户端扫描

java
@Configuration
@EnableHttpClients(basePackages = "com.example.client")
public class AppConfig {
}

定义客户端接口

java
@HttpClient(baseUrl = "${api.user-service.url}")
public interface UserServiceClient {
    
    @GET("/users/{id}")
    User getUser(@PathParam("id") Long id);
    
    @GET("/users")
    List<User> listUsers(@QueryParam("page") int page, 
                         @QueryParam("size") int size);
    
    @POST("/users")
    User createUser(@Body User user);
    
    @PUT("/users/{id}")
    User updateUser(@PathParam("id") Long id, @Body User user);
    
    @DELETE("/users/{id}")
    void deleteUser(@PathParam("id") Long id);
}

使用客户端

java
@Service
public class UserService {
    
    @Autowired
    private UserServiceClient userClient;
    
    public User findUser(Long id) {
        return userClient.getUser(id);
    }
}

配置

yaml
lcgyl:
  http-client:
    default:
      connect-timeout: 5s
      read-timeout: 30s
      retry:
        enabled: true
        max-attempts: 3
        delay: 1s
    
    # 针对特定客户端配置
    clients:
      userServiceClient:
        connect-timeout: 3s
        read-timeout: 10s

api:
  user-service:
    url: https://api.example.com

请求拦截器

内置拦截器

java
// 日志拦截器(自动启用)
// 记录请求/响应日志

// 追踪拦截器(自动启用)
// 传递 TraceId 到下游服务

自定义拦截器

java
@Component
public class AuthInterceptor implements RequestInterceptor {
    
    @Autowired
    private TokenService tokenService;
    
    @Override
    public void apply(RequestTemplate template) {
        String token = tokenService.getCurrentToken();
        template.header("Authorization", "Bearer " + token);
    }
}

高级功能

自定义编解码器

java
@HttpClient(
    baseUrl = "${api.service.url}",
    encoder = XmlEncoder.class,
    decoder = XmlDecoder.class
)
public interface XmlServiceClient {
    // ...
}

响应处理

java
@HttpClient(baseUrl = "${api.service.url}")
public interface ApiClient {
    
    // 返回完整响应
    @GET("/data")
    HttpResponse<Data> getDataWithResponse();
    
    // 返回响应头
    @GET("/data")
    @Headers({"Accept: application/json"})
    Data getData();
}

Actuator 端点

http
GET /actuator/http-clients

响应示例:

json
{
  "clients": [
    {
      "name": "userServiceClient",
      "baseUrl": "https://api.example.com",
      "status": "UP",
      "requestCount": 1234,
      "errorCount": 5
    }
  ]
}

下一步

Released under the Apache License 2.0