如何在Quarkus项目中用Apache Camel实现分页API调用
基于Apache Camel实现API分页循环获取数据
你的场景是用Quarkus+Apache Camel对接带分页的外部API,要根据返回的totalSize、limit、offset循环获取所有数据并保存到数据库。下面直接给你修改后的路由实现,核心是用Camel的loopDoWhile组件实现动态循环:
核心思路
- 初始化分页起始偏移量
offset为0 - 用
loopDoWhile判断:只要当前offset小于totalSize,就继续循环调用API - 每次调用后解析响应,处理数据,然后更新
offset(offset += limit)
修改后的完整路由代码
@RegisterForReflection @ApplicationScoped public class SalesForceAccountRouter extends BaseRouter { @Inject AccountRepository accountRepository; @Override public void configure() throws Exception { super.configure(); from("direct:salesforce-account") .removeHeaders("*") // 初始化分页参数:offset初始为0,limit可从配置或API响应获取,这里先从配置取 .setProperty("offset", constant(0)) .setProperty("limit", simple("{{sales.s.limit}}")) // 循环:只要offset < totalSize就继续 .loopDoWhile(simple("${exchangeProperty.offset} < ${exchangeProperty.totalSize}")) .log("Fetching records from SF Account with offset: ${exchangeProperty.offset}, limit: ${exchangeProperty.limit}") // 动态拼接请求URL,带入offset和limit(如果原query有其他参数,可合并到这里) .toD("{{sales.s.url}}/accounts?offset=${exchangeProperty.offset}&limit=${exchangeProperty.limit}") .unmarshal().json(JsonLibrary.Gson, PaginationResponse.class) // 处理数据:保存到数据库 .process(new SalesForceAccountProcessor(accountRepository)) // 更新totalSize(第一次调用后获取)和offset .setProperty("totalSize", simple("${body.totalSize}")) .setProperty("offset", simple("${exchangeProperty.offset} + ${exchangeProperty.limit}")) .end() .marshal().json(JsonLibrary.Gson) .log("All records fetched and processed, end route"); } }
关键细节说明
loopDoWhile的条件表达式:通过simple语言判断当前偏移量是否小于总记录数,满足则继续循环- 分页参数管理:用
exchangeProperty存储offset、limit、totalSize,保证循环过程中参数可动态更新 - 请求URL拼接:用
toD动态生成带分页参数的请求地址,替代原来的exchangeProperty.query(如果原query包含其他筛选参数,可以直接合并到URL中) - 数据处理:
SalesForceAccountProcessor负责将records列表保存到数据库,原有逻辑无需改动
注意事项
- 确保
PaginationResponse类包含totalSize、limit、offset和records对应的字段,Gson才能正确解析响应 - 如果外部API返回的
limit和请求值不一致,要以API返回的limit为准更新offset,避免出现偏移量计算错误
内容的提问来源于stack exchange,提问作者anonymous
相关产品推荐
相关产品推荐

