我在Spring Boot项目中使用Spring Webflux和ReactiveMongoRepository,并且我希望每个通量都是对象列表,如下所示:
// 1st Flux Started:
[
{
// 1st Dashboard
},
{
// 2nd Dashboard
}
]
// 1st Flux Ended
// 2nd Flux Started:
[
{
// 1st Dashboard
},
{
// 2nd Dashboard
}
]
// 2nd Flux Ended
存储库:
@Repository
public interface ReactiveDashboardRepository extends ReactiveMongoRepository<Dashboard, String> {
}
服务:
@Service
public class ReactiveDashboardServiceImpl implements ReactiveDashboardService {
private ReactiveDashboardRepository reactiveDashboardRepository;
public ReactiveDashboardServiceImpl(ReactiveDashboardRepository reactiveDashboardRepository) {
this.reactiveDashboardRepository = reactiveDashboardRepository;
}
public Flux<Dashboard> getDashboards() {
return this.reactiveDashboardRepository.findAll();
}
}
控制器:
@CrossOrigin
@RestController
@RequestMapping("/api/sse")
public class ReactiveDashboardRestController {
private ReactiveDashboardService reactiveDashboardService;
public ReactiveDashboardRestController(ReactiveDashboardService reactiveDashboardService) {
this.reactiveDashboardService = reactiveDashboardService;
}
@GetMapping(value = "/dashboards", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Dashboard> getDashboards() {
return this.reactiveDashboardService.getDashboards();
}
}
因此,基本上,我希望数组中的所有对象成为单个流的一部分,因为这是我将要使用的客户端应用程序的设计方式。到目前为止,总共只有3个。因此,在每个流中将保存所有对象的数组。我知道这不是webflux的最佳用法。 如果可以实现,该如何实现?
答案 0 :(得分:0)
如果要无限大的磁通以间隔发送数据,则需要函数“ interval”。
为简单起见,我建议直接在List中返回仪表板,并在Controller中以Flux转换List。
它将是这样的:
List<Dashboard> lDashBoard = new ArrayList<Dashboard>(Arrays.asList(
Dashboard.builder().name("Dash1").build(),
Dashboard.builder().name("Dash2").build(),
Dashboard.builder().name("Dash3").build()
));
Flux<List<Dashboard>> intervalFlux = Flux
.interval(Duration.ofMillis(500))
.map(tick -> {
return lDashBoard;
});
intervalFlux.subscribe(t->log.info("Dashboards:{}", lDashBoard));
输出如下:
2018-11-14 15:55:18.575 INFO [Dashboards:[Dashboard(name=Dash1), Dashboard(name=Dash2), Dashboard(name=Dash3)]
2018-11-14 15:55:19.073 INFO [Dashboards:[Dashboard(name=Dash1), Dashboard(name=Dash2), Dashboard(name=Dash3)]
2018-11-14 15:55:19.573 INFO [Dashboards:[Dashboard(name=Dash1), Dashboard(name=Dash2), Dashboard(name=Dash3)]