使用WebClient发送请求时如何让请求体的start参数每次调用递增10
实现方案
要实现每次请求时start字段在上次基础上自动加10,你可以通过维护一个线程安全的自增变量实现,具体代码如下:
1. 封装请求逻辑
将WebClient请求封装为可复用的服务类,用AtomicInteger存储当前的start初始值,保证多线程场景下的计数正确性:
import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import java.net.URI; import java.util.concurrent.atomic.AtomicInteger; @Service public class ProductRequestService { // 存储上次请求使用的start值,初始为1,线程安全 private final AtomicInteger currentStart = new AtomicInteger(1); // WebClient线程安全,全局复用一个实例即可 private final WebClient webClient = WebClient.create(); public Product sendQueryRequest() { // 读取本次要使用的start值,读取后自动加10更新为下次的初始值 int startForThisRequest = currentStart.getAndAdd(10); RequestDTO requestBody = new RequestDTO( "getAll", new RequestDataDto(startForThisRequest, 60) ); try { return webClient.post() .uri(new URI("myURL")) .header("sid", "mySid") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .bodyValue(requestBody) .retrieve() .bodyToMono(Product.class) .block(); } catch (Exception e) { // 按需添加:如果请求失败不需要消耗增量,可回滚start值 currentStart.addAndGet(-10); throw new RuntimeException("请求发送失败", e); } } }
2. 扩展说明
- 如果仅在单线程场景下使用,也可以用普通int类型存储
currentStart,AtomicInteger适用于多线程并发调用的场景避免计数错误。 - 如果需要服务重启后仍能延续之前的
start计数,可以将currentStart的值持久化到数据库、Redis等存储介质中,每次请求前读取最新值,使用后更新存储的数值即可。 - 如果需要调整增量大小,修改
getAndAdd方法的参数即可。
内容的提问来源于stack exchange,提问作者AlexWhite
相关产品推荐
相关产品推荐

