赞
踩
创建一个任务队列来存储提交的计算任务。
- @Component
- public class TaskQueue {
- private final Queue<CalculationTask> queue = new LinkedList<>();
-
- public synchronized void addTask(CalculationTask task) {
- queue.add(task);
- }
-
- public synchronized CalculationTask getNextTask() {
- return queue.poll();
- }
- }
- @Service
- public class CalculationService {
-
- @Autowired
- private TaskQueue taskQueue;
-
- @Autowired
- private CacheManager cacheManager;
-
- public void submitTask(CalculationTask task) {
- taskQueue.addTask(task);
- }
-
- @Async
- public void processTasks() {
- while (true) {
- CalculationTask task = taskQueue.getNextTask();
- if (task != null) {
- Result result = performCalculation(task);
- cacheManager.put(task.getId(), result);
- }
- }
- }
-
- public Result getResultFromCache(String taskId) {
- return cacheManager.get(taskId);
- }
-
- private Result performCalculation(CalculationTask task) {
- // Perform long-running calculation here
- // ...
- return new Result();
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- @Component
- public class CacheManager {
- private final Map<String, Result> cache = new ConcurrentHashMap<>();
-
- public void put(String key, Result result) {
- cache.put(key, result);
- }
-
- public Result get(String key) {
- return cache.get(key);
- }
- }
前端通过API提交计算任务,并获取一个任务ID。
- async function submitTask() {
- const response = await fetch('/submitTask', {
- method: 'POST',
- body: JSON.stringify({ /* task data */ }),
- headers: {
- 'Content-Type': 'application/json'
- }
- });
- const data = await response.json();
- const taskId = data.taskId;
- return taskId;
- }
前端通过任务ID获取计算结果。
- async function getResult(taskId) {
- const response = await fetch(`/getResult?taskId=${taskId}`);
- const data = await response.json();
- return data.result;
- }
- async function handleTask() {
- const taskId = await submitTask();
- // Poll or use a WebSocket to check if the task is completed
- const result = await getResult(taskId);
- // Use the result
- }
这个设计方案通过任务队列、异步处理和缓存管理器实现了任务提交、计算和结果缓存。前端可以通过任务ID来轮询或使用WebSocket来检查任务是否完成,并从缓存中获取结果,从而减少计算时间和资源消耗。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。