英文:
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 类
@RestController
public class controller {
@Autowired
Service service;
public void foo() {
service.foo(..parms, (message/*任何参数您想要*/) -> {
// 这里是将从服务接收消息的主体
System.out.print(message);
});
}
}
Service 类
public class Service {
// updateStatus 在这里是您将从服务发送更新到控制器的函数
public void foo(...params, updateStatus) {
updateStatus("开始处理...");
// 执行一些代码
updateStatus("进行中...");
// 执行一些代码
updateStatus("已完成");
}
}
英文:
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
@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);
});
}
}
Service Class
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");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论