// Inside your CSV processing logic StringtransactionId="TXN-123"; // Replace with the actual transaction ID StringprogressMessage="Processing 50% complete"; // Replace with your progress message
// Send an SSE update to the client sseController.sendSseUpdate(transactionId, progressMessage);
@PostMapping("/csv") public ResponseEntity<String> uploadCsv(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ResponseEntity.badRequest().body("Please select a CSV file to upload."); }
if (!isCsvValid(file)) { return ResponseEntity.badRequest().body("Invalid CSV file format or data."); }
//1. Start asynchronous processing and return a CompletableFuture CompletableFuture<Void> processingFuture = CompletableFuture.runAsync(() -> { asyncProcessCsv(file, transactionId); });
//2. Return a 202 (Accepted) response with the transaction ID return ResponseEntity.status(HttpStatus.ACCEPTED).body(transactionId); }
privatebooleanisCsvValid(MultipartFile file) { // Add your CSV validation logic here // Return true if the CSV is valid; otherwise, return false returntrue; }
<!DOCTYPE html> <html> <head> <title>Asynchronous Order Processing</title> </head> <body> <h1>Asynchronous Order Processing</h1> <buttononclick="processOrder()">Process Order</button> <divid="result"></div>
<script> let eventSource = null; asyncfunctionprocessOrder() { const orderRequest = { csvFilePath: "Path" }; try { const response = awaitfetch('/api/upload/csv', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(orderRequest) }); if (response.status === 202) { document.getElementById('result').textContent = 'Order processing initiated. Waiting for completion...'; const transactionId =response.result.transactionId; // Connect to the SSE endpoint for this order const eventSource = newEventSource(`/sse/stream?transactionId=${transactionId}`); eventSource.onmessage = (event) => { document.getElementById('result').textContent = event.data; }; eventSource.onerror = (error) => { console.error('SSE Error:', error); }; } } catch (error) { console.error('Error:', error); } } functioncloseEventSource() { if (eventSource) { eventSource.close(); eventSource = null; } } // Close the SSE connection when leaving the page window.addEventListener('beforeunload', closeEventSource); </script> </body> </html>
结论
在当下应用程序开发领域,快速响应能力和实时通信是至关重要的。异步 API 设计及其一系列技术实现(例如:Callbacks、WebSocket、消息队列和服务端事件发送(SSE))使开发人员能够快速构建面向用户提供实时数据更新和通知的应用程序。在我们现实生活中的电子商务案例中,SSE 被证明是一个颠覆性技术实现,能够为客户提供实时进度更新和数据通知,同时能够优化性能和用户体验。
当我们再思考异步 API 领域设计时,我们需要考虑应用程序的需求场景,并选择最符合我们需要的目标方法。无论是让用户了解产品更新还是在协作平台中实时协作,掌握这些异步技术将使我们的应用程序在当今瞬息万变的数字世界中脱颖而出。