在Mono上使用elapsed()函数的工作?

时间:2019-07-10 11:02:02

标签: java spring-webflux project-reactor spring-data-redis-reactive

我正在尝试获取执行时间以便在反应式编程中从redis读取内容,在查找文档时,我可以看到elapsed()方法将执行与以下相同且已实现的代码。

Flux.fromIterable(getActions(httpHeaders))
                .parallel()
                .runOn(Schedulers.parallel())
                .flatMap(actionFact -> methodToReadFromCache(actionFact))
                .sequential();

public Mono<ActionFact> methodToReadFromCache(actionFact) {
    return Mono.fromCallable(() -> getKey(actionFact))
                .flatMap(cacheKey ->
                  redisOperations.hasKey(key)
                                .flatMap(aBoolean -> {
                                    if (aBoolean) {
                                        return redisOperations.opsForValue().get(cacheKey);
                                    }
                                    return authzService.getRolePermissions(actionFact)
                                            .flatMap(policySetResponse ->
                                                    //save in cache
                                            );
                                })
                                .elapsed()
                                .flatMap(lambda -> {
                                    LOG.info("cache/service processing key:{}, time:{}", key, lambda.getT1());
                                    return Mono.just(lambda.getT2());
                                });

输出:

cache/service processing key:KEY1, time:3 
cache/service processing key:KEY2, time:4 
cache/service processing key:KEY3, time:18 
cache/service processing key:KEY4, time:34 
cache/service processing key:KEY5, time:46 
cache/service processing key:KEY6, time:57 
cache/service processing key:KEY7, time:70 
cache/service processing key:KEY8, time:81 
cache/service processing key:KEY9, time:91 
cache/service processing key:KEY10, time:103
cache/service processing key:KEY11, time:112
cache/service processing key:KEY12, time:121
cache/service processing key:KEY13, time:134
cache/service processing key:KEY14, time:146
cache/service processing key:KEY15, time:159

我希望每个缓存请求所花费的时间将少于<5毫秒,就像第一个和第二个请求一样,但不是这样。 elapsed()是否将当前的获取时间添加到累计时间?根据我的理解,流量产生的每个项目都是独立的吗?

2 个答案:

答案 0 :(得分:0)

根据文档

  

我想将排放与测量的时间(Tuple2<Long, T>)相关联...

     
      
  • 自订阅以来:已用

  •   
  • 从时间(计算机时间)开始:时间戳

  •   

elapsed是自订阅以来的测量时间。因此,您订阅并开始发射,自订阅服务以来,时间就会增加。

official docs

答案 1 :(得分:0)

Mono#elapsed衡量了Mono被订阅到Mono发出项目(onNext)的时间。

在您的情况下,导致预订和计时器启动的原因是调用flatMap的外部并行化methodToReadFromCache

导致onNext的原因是hasKey和if / else部分(redisOperations.opsForValue().get(cacheKey)authzService)的组合。

由于我们处于并行模式,因此外部flatMap至少应与CPU数量一样多的计时器。

但时间偏斜的事实可能暗示某些东西正在阻塞或容量有限。例如,是否redisTemplate一次只能处理几个键?