设计前后端系统以处理长时间运行的计算任务并提供缓存支持

后端设计

1. 任务队列

创建一个任务队列来存储提交的计算任务。

复制代码
@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();
    }
}
2. 计算服务
复制代码
@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();
    }
}
3. 缓存管理器
复制代码
@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);
    }
}

前端设计

1. 提交任务

前端通过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;
}
2. 获取结果

前端通过任务ID获取计算结果。

复制代码
async function getResult(taskId) {
    const response = await fetch(`/getResult?taskId=${taskId}`);
    const data = await response.json();
    return data.result;
}
3. 使用缓存
复制代码
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来检查任务是否完成,并从缓存中获取结果,从而减少计算时间和资源消耗。

相关推荐
用户27050777252412 分钟前
MCP 最小 Server 实测:3 个 JSON-RPC 报错与修法
前端
SL_staff13 分钟前
从配置失效到逻辑复用:JVS-Logic 如何构建可治理的业务编排中枢
java·spring·产品
用户4993350250714 分钟前
一人VIP账号多人共用:Web 代理里的会话共享怎么实现
前端
特立独行的猫A14 分钟前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
用户老李15 分钟前
无线电自学教程 05:第一台收音机——从矿石机到 SDR
前端
IPIPD23 分钟前
Node.js请求遇到503怎么重试?先解析Retry-After,再做有上限退避
前端
葡萄城技术团队29 分钟前
dsh-spreadjs-editor 的集成链路:把 SpreadJS Designer 嵌进 Agent 工作台
前端
文丑颜不良啊1 小时前
LeetCode1961~1980题目解析
java·leetcode
FlyWIHTSKY1 小时前
vue2和vue3有什么区别,用法上有哪些区别
前端·javascript·vue.js
码云之上1 小时前
10 颗一模一样的「Edit」:中后台 Web Agent 怎么找到对的那一行
前端·人工智能·浏览器