You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 15:15:03