feat: 实现基于 Redis 的延迟任务队列和工作器,支持周期性交易处理等后台任务调度。

This commit is contained in:
2026-01-28 16:36:56 +08:00
parent a9ee8856ba
commit 5ff680ee43
6 changed files with 884 additions and 0 deletions

View File

@@ -0,0 +1,78 @@
package handler
import (
"net/http"
"accounting-app/internal/mq"
"github.com/gin-gonic/gin"
)
// TaskQueueHandler 任务队列状态查询 Handler
type TaskQueueHandler struct {
taskSystem *mq.RecurringTaskSystem
}
// NewTaskQueueHandler 创建任务队列 Handler
func NewTaskQueueHandler(taskSystem *mq.RecurringTaskSystem) *TaskQueueHandler {
return &TaskQueueHandler{
taskSystem: taskSystem,
}
}
// GetStats 获取任务队列统计信息
// GET /api/v1/admin/tasks/stats
func (h *TaskQueueHandler) GetStats(c *gin.Context) {
if h.taskSystem == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{
"success": false,
"error": "Task system not available (Redis required)",
})
return
}
stats := h.taskSystem.GetStats(c.Request.Context())
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": stats,
})
}
// GetPendingTasks 获取即将执行的任务列表
// GET /api/v1/admin/tasks/pending
func (h *TaskQueueHandler) GetPendingTasks(c *gin.Context) {
if h.taskSystem == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{
"success": false,
"error": "Task system not available (Redis required)",
})
return
}
tasks, err := h.taskSystem.Queue.GetPendingTasks(c.Request.Context(), 50)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"error": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"count": len(tasks),
"tasks": tasks,
},
})
}
// RegisterRoutes 注册路由
func (h *TaskQueueHandler) RegisterRoutes(rg *gin.RouterGroup) {
tasks := rg.Group("/admin/tasks")
{
tasks.GET("/stats", h.GetStats)
tasks.GET("/pending", h.GetPendingTasks)
}
}