gpt4 book ai didi

java - 如何在 Spring 创造 react 堆热流?

转载 作者:太空宇宙 更新时间:2023-11-04 09:15:28 28 4
gpt4 key购买 nike

我有以下代码。我认为通过发布我可以创建一个热流,但是每个连接上的 uniqueId 都不同。我希望 create 方法执行一次,然后作为任意数量的订阅者的热流运行。

    private Date lastChecked = Calendar.getInstance().getTime();

@GetMapping(path = "/news/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Object> comments(@RequestParam(required=false) String date) throws ParseException {
if(date != null) {
lastChecked=new SimpleDateFormat("dd-MM-yyyy").parse(date);
}
return Flux.create(fluxSink -> {
String uniqueID = UUID.randomUUID().toString();
Flux.interval(Duration.ofSeconds(1))
.map(s -> {
System.out.println(uniqueID);
this.newsRepository.findByTimestampGreaterThanOrderByTimestampDesc(lastChecked).take(5).doOnEach(new Consumer<Signal<News>>() {
@Override
public void accept(Signal<News> commentSignal) {
fluxSink.next(commentSignal.get());
}
}).subscribe();
lastChecked = Calendar.getInstance().getTime();
lastChecked.setTime(lastChecked.getTime() - 2000);
return s;
})
.subscribe();
})
.publishOn(Schedulers.parallel())
.onBackpressureBuffer()
.publish() //executing publish here
.autoConnect();
}

最佳答案

我找到了解决方案,使用 PostConstruct 注释仅创建一次 ConnectableFlux:

    private Date lastChecked = Calendar.getInstance().getTime();
private ConnectableFlux<Object> flux;

@PostConstruct
public void load()
{
System.out.println("Loaded");
this.flux = Flux.create(fluxSink -> {
String uniqueID = UUID.randomUUID().toString();
Flux.interval(Duration.ofSeconds(1))
.map(s -> {
System.out.println(uniqueID);
this.newsRepository.findByTimestampGreaterThanOrderByTimestampDesc(lastChecked).take(5).doOnEach(new Consumer<Signal<News>>() {
@Override
public void accept(Signal<News> commentSignal) {
fluxSink.next(commentSignal.get());
}
}).subscribe();
lastChecked = Calendar.getInstance().getTime();
lastChecked.setTime(lastChecked.getTime() - 2000);
return s;
})
.subscribe();
}).publishOn(Schedulers.parallel())
.onBackpressureBuffer()
.publish();
}

@GetMapping(path = "/news/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Object> comments(@RequestParam(required=false) String date) throws ParseException {

return flux.autoConnect();
}

关于java - 如何在 Spring 创造 react 堆热流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59079171/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com