标签: reactive-programming

以响应式方式使用分页 API

我试图弄清楚如何以反应式方式使用分页 API,公开项目流而不是 API 提供给我的页面。

我拥有的 - 分页 API

Slack API(以及许多其他 API)使用某种形式的元数据对象处理分页,以便在查询时/api/stuff返回一个如下所示的对象:

{
    "items": [ <list of first page you requested> ],
    "meta": {
        "cursor": "<a cursor string to get the next page>"
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用 请求下一页GET /api/stuff?cursor=<the cursor from above>,在响应中您将获得一个新的光标,因此您可以继续下去,直到收到光标为空的响应 - 这就是最后一个可用页面。

我想要什么 - 一系列物品

对于 Reactor,我想提供一种具有返回类型的方法Flux<Item>,即所有项目的流,其中消费者不需要知道或关心这些项目实际上一次一页地获取。

基本上,我想做一些事情,它需要一个初始状态和一个带有签名State -> Mono<Tuple2<Collection<Item>, State>>(或等效)的方法,并Flux<Item>通过顺序获取新页面来给我一个,直到State指示我们完成为止。

我尝试使用Flux.createor来制定某些内容Flux.generate,但它们的用例似乎与我的略有不同。

我如何到达那里?

java pagination reactive-programming project-reactor

6
推荐指数
1
解决办法
1920
查看次数

doOnNext() 不会被调用 Spring Webflux

我是反应式编程和 Spring Webflux 的新手,我有一种方法可以从 Redis 获取一些密钥,如果该密钥为 null 或不等于指定的字符串,我想抛出异常,但嵌套的 donOnNext 方法不会被调用并被customerRepository.save(customer)触发,而必须抛出异常并打破链条。有人可以向我解释一下 Reactor API 在我的例子中是如何表现的吗?

这是我的方法:

@Override
public Mono<RegistrationVerificationResDTO> verifyCustomerAndGenerateToken(Mono<VerifyOtpReqDTO> verifyOtpReqDTO) {
    return verifyOtpReqDTO
            .doOnNext(verifyDTO -> reactiveRedisOperations
                    .opsForValue()
                    .get(RedisDictionary.OTP_KEY + verifyDTO.getPhoneNumber())
                    .filter(otp -> otp.equalsIgnoreCase(verifyDTO.getOtp()))
                    .switchIfEmpty(Mono.error(ForbiddenException::new)))
            .map(verifyDTO -> customerRepository.findById(verifyDTO.getId())
                    .orElseThrow(() -> new NotFoundException("Customer not found")))
            .doOnNext(customer -> {
                customer.setVerified(true);
                customerRepository.save(customer);
            })
            .map(customer -> new RegistrationVerificationResDTO().setAccessToken("accessToken")
                    .setRefreshToken("refreshToken")
                    .setCustomer(customer));
}
Run Code Online (Sandbox Code Playgroud)

更新:我意识到如果我们在 doOnNext 方法中创建另一个发布者,因为 spring 仅订阅最外层的发布者,内部发布者不会被触发我已经更新了我的代码,但它仍然不起作用。

java reactive-programming spring-boot project-reactor spring-webflux

6
推荐指数
1
解决办法
5712
查看次数

无阻塞地通量到 List&lt;Objects&gt;

寻找将 Flux 转换为List<Object>. 如果我使用 block() 会出现错误。因此,需要在不阻塞呼叫的情况下进行通话。

Flux.from(Collection.find())
Run Code Online (Sandbox Code Playgroud)

使用反应式编程,但 graphql 期望List<objects>返回 Flux 并出错。

使用 Block() 编写代码

public List<Test> findAll() {
        return Flux.from(testCollection.find()).collectList().block();

}
Run Code Online (Sandbox Code Playgroud)

错误 :-

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-kqueue-7
Run Code Online (Sandbox Code Playgroud)

在这里,我需要返回,因为由于某种原因List<Test>我无法发送。Flux<Test>

java reactive-programming project-reactor graphql-java

6
推荐指数
1
解决办法
2万
查看次数

如何将 Flux&lt;Object&gt; 列表转换为 List&lt;Object&gt;

我有一个 Flux,我想将其转换为 List。我怎样才能做到这一点?

Flux<Object> getInstances(String serviceId); // Current one 
List<Object> getInstances(String serviceId); // Demanded one
Run Code Online (Sandbox Code Playgroud)

Java 8 或反应式组件有一个准备好的方法将其映射或转换为 List ??

我应该使用.map()

final List<ServiceInstance> sis = convertedStringList.parallelStream()
            .map( this.reactiveDiscoveryClient::getInstances )
            // It should be converted to List<Object>
Run Code Online (Sandbox Code Playgroud)

reactive-programming java-8 java-stream project-reactor reactive

6
推荐指数
1
解决办法
9273
查看次数

如何在Webflux应用程序中使Spring Cloud Stream消费者?

我有一个基于 Webflux 的微服务,它有一个简单的反应存储库:

    public interface NotificationRepository extends ReactiveMongoRepository<Notification, ObjectId> {
    }
Run Code Online (Sandbox Code Playgroud)

现在我想扩展这个微服务来使用来自 Kafka 的事件消息。然后该消息/事件将被保存到数据库中。

对于 Kafka 监听器,我使用了 Spring Cloud Stream。我创建了一些简单的消费者,它工作得很好 - 我能够使用消息并将其保存到数据库中。

    @Bean
    public Consumer<KStream<String, Event>> documents(NotificationRepository repository) {
        return input ->
                input.foreach((key, value) -> {
                    LOG.info("Received event, Key: {}, value: {}", key, value);
                    repository.save(initNotification(value)).subscribe();
                });
    }
Run Code Online (Sandbox Code Playgroud)

但这是连接 Spring Cloud Stream 消费者和反应式存储库的正确方法吗?看起来不像是我subscribe()最后必须打电话的时候。

我阅读了Spring Cloud Stream 文档(针对 3.0.0 版本),他们说

Native support for reactive programming - since v3.0.0 we no longer distribute spring-cloud-stream-reactive modules and instead relying on …
Run Code Online (Sandbox Code Playgroud)

reactive-programming apache-kafka project-reactor spring-cloud-stream spring-webflux

6
推荐指数
1
解决办法
4619
查看次数

Spring Webflux 在响应式堆栈中使用阻塞 HttpClient

我目前正在进行一个构建微服务的项目,并尝试从更传统的 Spring Boot 迁移RestClient到使用 Netty 并WebClient作为 HTTP 客户端的反应式堆栈,以便连接到后端系统。

WebClient这对于使用 REST API 的后端来说进展顺利,但是在实现连接到 SOAP 后端和 Oracle 数据库的服务时仍然遇到一些困难,这些数据库仍然使用传统的 JDBC。

我设法在网上找到一些关于 JDBC 调用的解决方法,这些方法利用并行调度程序来发布阻塞 JDBC 调用的结果:

//the method that is called by @Service
@Override
public Mono<TransactionManagerModel> checkTransaction(String transactionId, String channel, String msisdn) {
    return asyncCallable(() -> checkTransactionDB(transactionId, channel, msisdn))
            .onErrorResume(error -> Mono.error(error));
}

...

//the actual JDBC call
private TransactionManagerModel checkTransactionDB(String transactionId, String channel, String msisdn) {
...
    List<TransactionManagerModel> result = 
                    jdbcTemplate.query(CHECK_TRANSACTION, paramMap, new BeanPropertyRowMapper<>(TransactionManagerModel.class));
...
}

//Generic async …
Run Code Online (Sandbox Code Playgroud)

java spring reactive-programming spring-boot spring-webflux

6
推荐指数
1
解决办法
7756
查看次数

使用 spring-data-mongodb-reactive 进行批量操作

是否可以使用 ReactiveMongoTemplate 或 spring-data-mongodb-reactive 执行 MongoDB 批量操作(如更新/更新插入)?

reactive-programming spring-data-mongodb spring-data-mongodb-reactive

6
推荐指数
0
解决办法
270
查看次数

MutableStateFlow 不适用于 MutableList

这是我尝试使用的 MutableStateFlow 值:

val songList: MutableStateFlow<MutableList<Song>> = MutableStateFlow(arrayListOf())
Run Code Online (Sandbox Code Playgroud)

我需要观察上面 MutableList 上的更改(在 add、removeAt 等方法之后),但无法实现这一点。我的猜测是,因为只有列表的元素发生变化,而不是列表本身发生变化,所以不会触发收集方法。

如果可能的话,如何使用 StateFlow 实现这一目标?如果不是,正确的做法是什么?

请注意,我需要 arrayListOf() 的初始值,因此 LiveData 对我来说可能不够。

android reactive-programming android-livedata kotlin-stateflow

6
推荐指数
1
解决办法
4162
查看次数

Thymeleaf webflux:仅允许将一个数据驱动变量指定为模型属性,但至少已识别两个

我正在尝试创建一个仪表板应用程序,其中多个小部件通过 SSE 获取更新。我的 DashboardController 看起来像:

public class DashboardController
{
    private WidgetService widgetService;

    public DashboardController(WidgetService widgetService)
    {
        this.widgetService = widgetService;
    }

    @GetMapping("/")
    public String index(final Model model)
    {
        for(WidgetInterface<?> widget : widgetService.getAll()) {
            model.addAttribute("widget-data-driver-" + widget.getIdentifier(),
                    new ReactiveDataDriverContextVariable(widget.getInitialData(), 100));
        }
        model.addAttribute("widgets", widgetService.getAll());
        return "index";
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的小部件界面:

public interface WidgetInterface<T>
{
    public String getIdentifier();
    public String getTitle();
    public String getStreamEndpoint();
    public Flux<T> getInitialData();
    public Map<String, String> getColumns();
    public String getThymeLeafFraction();
    public Date getLastItemDate();
    public Flux<T> getItemsUpdatedSince(Date date);
}
Run Code Online (Sandbox Code Playgroud)

一个小部件(来自 WidgetService)一切正常。我正在尝试将ReactiveDataDriverContextVariable …

java spring reactive-programming thymeleaf spring-webflux

6
推荐指数
1
解决办法
822
查看次数

Java Flux 中的延迟增加

我有一个代码,我可以在循环中执行一段逻辑,并使用 Flux 之间有一些延迟。像这样的事情,

Flux.defer(() -> service.doSomething())
            .repeatWhen(v -> Flux.interval(Duration.ofSeconds(10)))
            .map(data -> mapper(data)) //map data
            .takeUntil(v -> shouldContinue(v)) //checks if the loop can be terminated
            .onErrorStop();
Run Code Online (Sandbox Code Playgroud)

现在,我想要增量延迟。这意味着,在前 5 分钟内,每次执行之间的延迟可能为 10 秒。然后,在接下来的 10 分钟内,延迟可以是 30 秒。并且,此后每次执行之间的延迟可以是一分钟。

我如何使用 Flux 来实现这一目标?

提前致谢。

java delay reactive-programming flux spring-webflux

6
推荐指数
1
解决办法
439
查看次数