package main
import (
"encoding/json"
"fmt"
uuid "github.com/satori/go.uuid"
"github.com/streadway/amqp"
)
// CeleryTask 任务模型
type CeleryTask struct {
Queue string
TaskName string
Args []interface{}
Kwargs map[string]interface{}
}
// NewCelery 创建任务模型
func NewCelery(hosts string) (*Celery, error) {
var err error
var celery = new(Celery)
if celery.connect, err = amqp.Dial(hosts); err == nil {
if celery.channel, err = celery.connect.Channel(); err == nil {
return celery, err
}
}
return nil, err
}
// call 调用结构
var call = map[string]interface{}{"callbacks": nil, "errbacks": nil, "chain": nil, "chord": nil}
// Celery 消息队列连接
type Celery struct {
connect *amqp.Connection
channel *amqp.Channel
}
// Delay 发送任务
func (c *Celery) Delay(task *CeleryTask) (taskId string, err error) {
if task.Args == nil {
task.Args = []interface{}{}
}
var payload = []interface{}{task.Args, task.Kwargs, call}
body, err := json.Marshal(payload)
if err != nil {
return "", err
}
taskId = uuid.Must(uuid.NewV4()).String()
return taskId, c.channel.Publish("", task.TaskName, false, false,
amqp.Publishing{
ContentEncoding: "utf-8",
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
CorrelationId: taskId,
Headers: amqp.Table{"id": taskId, "root_id": taskId, "task": task.TaskName, "retries": 5},
Body: body,
},
)
}
func main() {
celery, err := NewCelery("amqp://admin:123456@127.0.0.1:5672/org")
if err != nil {
panic(err)
}
if taskId, err := celery.Delay(&CeleryTask{
Queue: "iowork",
TaskName: "iowork",
Kwargs: map[string]interface{}{"work_type": "export", "a1": 200, "a2": true},
}); err != nil {
panic(err)
} else {
fmt.Println(taskId)
}
}
11-11
464
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-03
206
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)