首页 > 解决方案 > 服务可以在 Spring Boot 中更新控制器以进行长进程吗

问题描述

这是一个更多关于spring boot中服务控制器注释类之间通信的问题。我有一个RestController类,它公开了一个调用Service类中的方法的 POST 映射。现在这个方法可能需要很长时间运行;因此需要向控制器发送某种反馈。

是否有任何机制允许服务调用/更新控制器中的方法/变量?

标签: javaspring

解决方案


最简单的方法之一是将一些lamda函数从控制器传递给服务,然后像这样从服务中调用它

控制器类

@RestController
public class controller {
    @Autowired
    Service service;

    public void foo() {
            service.foo(..parms, (message/*any params you want*/) -> {
                // here the body that will receive the message from the service
                System.out.print(message);
            });
    }
}

服务等级

public class Service {
    // updateStatus here is the function you will send the update to the controller from
    public void foo(...params, updateStatus) {
        updateStatus("starting the process...");
        // do some code
        updateStatus("in progress...");
        // do some code
        updateStatus("completed");
    }
}

推荐阅读