【问题标题】:Reactive calls in @PostConstruct function@PostConstruct 函数中的响应式调用
【发布时间】:2020-04-04 22:24:50
【问题描述】:

有人可以帮我做以下事情吗:

@PostContruct public void func() {
   webclient.get()...subscribe();
}

webclient 调用将在 func() 返回后终止。它很可能会在第一个请求到来之前发生,但不能保证。另一种选择是 block(),这违背了反应的目的。

在@PostConstruct 方法中进行响应式调用的正确方法是什么?

谢谢。

【问题讨论】:

    标签: java spring reactive-programming spring-webflux


    【解决方案1】:

    我创建了一个简单的 bean。

    同步更新:

    @Component
    public class BeanTest {
    
        private String postConstructValue;
    
        @PostConstruct
        public void init(){
            try {
                Thread.sleep(5000);
                this.postConstructValue = "Construction done";
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        @Scheduled(fixedRate = 500)
        public void print(){
            System.out.println(
                    this.postConstructValue
            );
        }
    
    }
    
    • 应用程序启动需要一些时间(超过 5 秒),因为我们在后期构造中模拟了一些耗时的过程。计划的打印方法仅在应用程序启动后才开始打印。它开始打印“施工完成”消息。

    异步更新:

    @Component
    public class BeanTest {
    
        private String postConstructValue;
    
        @PostConstruct
        public void init(){
            Flux.just("Construction done")
                    .delayElements(Duration.ofSeconds(5))
                    .subscribe(s -> this.postConstructValue = s);
        }
    
        @Scheduled(fixedRate = 500)
        public void print(){
            System.out.println(
                    this.postConstructValue
            );
        }
    
    }
    
    • 现在在这种方法中,应用程序在 2 秒内启动。打印方法开始打印null 几秒钟。然后它开始打印“施工完成”。它不会终止 Flux postConstruct 值更新。它是异步发生的。

    当您想要非阻塞行为并异步完成某事时,反应式方法很好。如果你认为你的组件创建应该等待正确的构造,你必须阻止!否则,您可以采用第二种方法。

    【讨论】:

    • 谢谢@vins。我想在这种情况下阻塞是可以接受的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多