springboot学习第11期 - @HttpExchange

@HttpExchange 是什么

@HttpExchange 是springboot3提供的声明式发送HTTP请求客户端工具。

使用

第一步:根据第三方服务的接口声明

假如有第三方接口api:http://localhost:8080/api/hello/{id}?name={name},返回String类型。

按照上面的格式,创建第三方Client接口:

java 复制代码
@HttpExchange("/api/hello")
public interface ThirdClient {

    @GetExchange("/{id}")
    String sayHello(@PathVariable("id") int id, 
                    @RequestParam(value = "name", defaultValue = "World") String name
    );

    // 也可以返回 ResponseEntity, 如果想要获取响应其他信息的话
    // @GetExchange("/{id}")
    // ResponseEntity<String> sayHello(@PathVariable("id") int id, 
    //                 @RequestParam(value = "name", defaultValue = "World") String name
    // );

}

第二步:注入实现类

java 复制代码
@Configuration
public class HttpExchangeConfig {

    @Bean
    public ThirdClient thirdClient(RestClient.Builder builder) {
        RestClient restClient = builder
                .baseUrl("http://localhost:8080")
                .build();

        HttpServiceProxyFactory factory = HttpServiceProxyFactory
                .builderFor(RestClientAdapter.create(restClient))
                .build();

        return factory.createClient(ThirdClient.class);
    }
}

第三步:调用

java 复制代码
@Autowired
private ThirdClient thirdClient;


String s = thirdClient.sayHello(1, "aaa");

异常处理

本质上还是引用了RestClient发送请求,所以异常还是和RestClient异常一样。

通用异常是 RestClientException

4xx异常:HttpClientErrorException

5xx异常:HttpServerErrorException

网络错误:ResourceAccessException

重试

可以结合 spring retry 注解达到重试的效果

java 复制代码
@HttpExchange("/api/hello")
public interface ThirdClient {

    @GetExchange("/{id}")
    @Retryable(retryFor = {RestClientException.class}, noRetryFor = {HttpClientErrorException.class}, maxAttempts = 3, backoff = @Backoff(delay = 5000), listeners = {"customRetryListener"})
    ResponseEntity<String> sayHello(@PathVariable("id") int id, @RequestParam(value = "name", defaultValue = "World") String name);

}

这里还注入了一个自定义重试监听器,当执行重试操作的时候,可以打印一些自定义日志。

java 复制代码
@Component
public class CustomRetryListener implements RetryListener {
    private static final Logger log = LoggerFactory.getLogger(CustomRetryListener.class);

    @Override
    public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
        // 第一次调用前触发
        log.info("开始重试操作 - 方法: {}", context.getAttribute(RetryContext.NAME));
        return true;
    }

    @Override
    public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        // 最后一次重试结束后触发(无论成功失败)
        if (throwable != null) {
            log.error("重试结束,最终失败 - 方法: {}, 异常: {}", context.getAttribute(RetryContext.NAME), throwable.toString());
        } else {
            log.info("重试结束,成功 - 方法: {}, 重试次数: {}", context.getAttribute(RetryContext.NAME), context.getRetryCount());
        }
    }

    @Override
    public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        // 每次重试失败后触发
        log.warn("重试失败 - 方法: {}, 第 {} 次重试, 异常: {}",
                context.getAttribute(RetryContext.NAME),
                context.getRetryCount(),
                throwable.toString());
    }
}
相关推荐
paopaokaka_luck6 分钟前
基于SpringBoot+Vue的数码交流管理系统(AI问答、协同过滤算法、websocket实时聊天、Echarts图形化分析)
vue.js·人工智能·spring boot·websocket·echarts
Seven9730 分钟前
Springboot 常见面试题汇总
java·spring boot
ღ᭄ꦿ࿐Never say never꧂1 小时前
微信小程序 Button 组件 open-type 完全指南:从用户信息获取到客服分享的实战应用
spring boot·微信小程序·小程序·uni-app·vue3
Query*2 小时前
Java 设计模式—— 责任链模式:从原理到 SpringBoot 最优实现
java·spring boot·责任链模式
摇滚侠12 小时前
Spring Boot 3零基础教程,Spring Boot 日志的归档与切割,笔记22
spring boot·redis·笔记
lang2015092812 小时前
Spring Boot开发利器:devtools全解析(续)
spring boot
皮皮林55112 小时前
SpringBoot启动优化7板斧:砍掉70%启动时间的魔鬼实践
spring boot
程序员小凯12 小时前
Spring Boot消息队列与事件驱动详解
java·spring boot·后端
计算机学姐13 小时前
基于微信小程序的垃圾分类管理系统【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
i学长的猫13 小时前
Spring Boot 布隆过滤器最佳实践指南
spring boot·后端·哈希算法