該專案的概述是這樣的:
- 通過端點將檔案上傳到 Springboot 服務器
- 端點在收到檔案時發送
OK回應,但繼續在后臺處理檔案,對檔案運行測驗。
因此,由于控制器的端點已經回傳了回應,我如何在不使用控制器的情況下將資訊從后端發送到前端。
這是控制器回傳回應后運行的內容:
CompletableFuture.runAsync(() -> {
int count = 0;
boolean stillProcessing = true;
while (stillProcessing) {
stillProcessing = !test.isTestComplete();
if (test.getNumberOfInstancesComplete() > count) {
count = test.getNumberOfInstancesComplete();
log.info("{}/{} instances completed so far", count, test.getInstances().size());
}
}
});
該log.info行是我需要回傳到前端 React 方面的內容。
最終目標是基本上使用列印的值向用戶顯示加載欄log.info()。
uj5u.com熱心網友回復:
您可以使用 websockets 在沒有控制器的情況下通知前端。這是隨時使用 STOMP 從后端向客戶端發送訊息的示例代碼。
@Component
public class PushMessage {
@Autowired
SimpMessagingTemplate simpMessagingTemplate;
public <T> void invokeWebSocketEndpoint(String endpoint, T payload) {
this.simpMessagingTemplate.convertAndSend(endpoint, payload);
}
}
有關 STOMP websockets 的更多資訊,請查看此鏈接 https://spring.io/guides/gs/messaging-stomp-websocket/
如果您不想在客戶端和服務器之間進行雙向通信,而只想從服務器向客戶端推送訊息,您也可以使用服務器發送的事件。這是一個簡單的例子。
@GetMapping(value = "/test")
public SseEmitter test() {
SseEmitter emitter = new SseEmitter();
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {
try {
Process p = Runtime.getRuntime().exec("ping -c 10 www.google.com");
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
emitter.send(line);
}
emitter.complete();
}
} catch (IOException e) {
emitter.completeWithError(e);
e.printStackTrace();
}
});
executorService.shutdown();
return emitter;
}
有關服務器發送事件的更多資訊,請參閱此 https://www.baeldung.com/spring-server-sent-events
您可以使用 EventSource API https://developer.mozilla.org/en-US/docs/Web/API/EventSource從前端使用服務器發送的事件
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/410507.html
標籤:
