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

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

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");
	}
}

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:

确定