java flux api,Spring WebFlux和WebClient进行了许多API调用

我做了类似的事情......我的目标是创建一个带有这样签名的方法:

Flux getIssues(WebClient webClient);

因为我打电话的网站只提供了分页界面,所以我需要将多个REST调用的结果提供给一个Flux . 以下是我的实施 . 请注意我使用CachedThreadPool .

Flux getIssues(WebClient webClient) {

return Flux.generate(

() -> new IssuesState(webClient),

(state, sink) -> {

BasicIssue ret = state.getNext();

if (ret == null) {

sink.complete();

} else {

sink.next(ret);

}

return state;

}

}

class IssuesState {

private final AtomicBoolean isDone = new AtomicBoolean(false);

private final AtomicInteger threadCount = new AtomicInteger(1);

private final Executor executor = Executors.newCachedThreadPool();

private final LinkedBlockingQueue issueQueue = new LinkedBlockingQueue();

public IssuesState(WebClient webClient) {

executor.execute(() -> getNextBlock(webClient, 0));

}

private void getNextBlock(final WebClient webClient, final int startAt) {

webClient

.get()

.uri(...)

.header("Authorization", "Basic " + Base64Utils.encodeToString(("username:password".getBytes(UTF_8))))

.accept(MediaType.APPLICATION_JSON)

.retrieve()

.bodyToMono(PageableIssue.class)

.subscribe(pageableIssue -> {

int maxResults = pageableIssue.getMaxResults();

int total = pageableIssue.getTotal();

if (startAt == 0) {

for (int i = startAt + maxResults; i < total; i += maxResults) {

threadCount.incrementAndGet();

final int x = i;

executor.execute(() -> getNextBlock(webClient, x));

}

}

synchronized (issueQueue) {

for (BasicIssue issue : pageableIssue.getIssues()) {

issueQueue.add(issue);

}

if (threadCount.decrementAndGet() == 0) {

isDone.set(true);

}

}

});

}

public BasicIssue getNext() {

synchronized (issueQueue) {

if (isDone.get() && issueQueue.isEmpty()) {

return null;

}

}

try {

return issueQueue.take();

} catch (InterruptedException e) {

e.printStackTrace();

}

return null;

}

}

使用上面的方法..

getIssues(webClient)

.subscribe(basicIssue -> System.out.println(basicIssue.getName());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值