一个服务能否在Spring Boot中更新长时间进程中的控制器

huangapple go评论132阅读模式
英文:

Can a service update a controller in Spring boot for long processes

问题

这是关于在Spring Boot中的服务(Service)控制器(Controller)注解类之间通信的问题。我有一个RestController类,暴露了一个POST映射,调用了Service类中的一个方法。现在这个方法可能会运行很长时间,因此需要向控制器发送某种反馈。

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

英文:

this is a question more about communication between service and controller annotated classes in spring boot. I have a RestController class that exposes a POST mapping which calls a method in the Service class. Now this method may take a long time running; hence there is a need to send some kind of feedback to the controller.

Is there any mechanism which allows a service to call/update a method/variable in the controller?

答案1

得分: 3

以下是翻译好的部分:

Controller 类

  1. @RestController
  2. public class controller {
  3. @Autowired
  4. Service service;
  5. public void foo() {
  6. service.foo(..parms, (message/*任何参数您想要*/) -> {
  7. // 这里是将从服务接收消息的主体
  8. System.out.print(message);
  9. });
  10. }
  11. }

Service 类

  1. public class Service {
  2. // updateStatus 在这里是您将从服务发送更新到控制器的函数
  3. public void foo(...params, updateStatus) {
  4. updateStatus("开始处理...");
  5. // 执行一些代码
  6. updateStatus("进行中...");
  7. // 执行一些代码
  8. updateStatus("已完成");
  9. }
  10. }
英文:

one of the most simplest ways is passing some lamda function from the controller to the service and call it from the service like this

Controller Class

  1. @RestController
  2. public class controller {
  3. @Autowired
  4. Service service;
  5. public void foo() {
  6. service.foo(..parms, (message/*any params you want*/) -> {
  7. // here the body that will receive the message from the service
  8. System.out.print(message);
  9. });
  10. }
  11. }

Service Class

  1. public class Service {
  2. // updateStatus here is the function you will send the update to the controller from
  3. public void foo(...params, updateStatus) {
  4. updateStatus("starting the process...");
  5. // do some code
  6. updateStatus("in progress...");
  7. // do some code
  8. updateStatus("completed");
  9. }
  10. }

huangapple
  • 本文由 发表于 2020年4月7日 16:33:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/61075888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定