104 lines
2.2 KiB
Go
104 lines
2.2 KiB
Go
package redisqueue
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
|
|
"be.ems/lib/log"
|
|
|
|
redisdb "be.ems/src/framework/database/redis"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// 写入 alarm_relation 消息
|
|
func AddAlarmRelationQueue(ids []string) error {
|
|
payload := map[string][]string{"ids": ids}
|
|
payloadBytes, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
values := map[string]interface{}{
|
|
"payload": string(payloadBytes),
|
|
}
|
|
|
|
_, err = client.XAdd(ctx, &redis.XAddArgs{
|
|
Stream: "alarm_relation",
|
|
Values: values,
|
|
}).Result()
|
|
|
|
// 只保留最新2000条消息
|
|
client.XTrimMaxLen(context.Background(), "alarm_relation", 2000).Result()
|
|
|
|
return err
|
|
}
|
|
|
|
// 写入 nbi_cm 消息
|
|
func AddNbiCMQueue(ids []string) error {
|
|
payload := map[string][]string{"ids": ids}
|
|
payloadBytes, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
values := map[string]interface{}{
|
|
"payload": string(payloadBytes),
|
|
}
|
|
_, err = client.XAdd(ctx, &redis.XAddArgs{
|
|
Stream: "nbi_cm",
|
|
Values: values,
|
|
}).Result()
|
|
|
|
// 只保留最新2000条消息
|
|
client.XTrimMaxLen(context.Background(), "nbi_cm", 2000).Result()
|
|
|
|
return err
|
|
}
|
|
|
|
// 写入 nbi_pm 消息
|
|
func AddNbiPMQueue(neType, id string) error {
|
|
payload := map[string]string{"neType": neType, "id": id}
|
|
payloadBytes, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
values := map[string]interface{}{
|
|
"payload": string(payloadBytes),
|
|
}
|
|
_, err = client.XAdd(ctx, &redis.XAddArgs{
|
|
Stream: "nbi_pm",
|
|
Values: values,
|
|
}).Result()
|
|
|
|
// 只保留最新2000条消息
|
|
client.XTrimMaxLen(context.Background(), "nbi_pm", 2000).Result()
|
|
|
|
return err
|
|
}
|
|
|
|
// 读取并打印指定 stream 的最新消息
|
|
func ReadLatest(stream string) error {
|
|
res, err := client.XRevRangeN(ctx, stream, "+", "-", 1).Result()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, msg := range res {
|
|
log.Tracef("Stream: %s, ID: %s, Values: %v\n", stream, msg.ID, msg.Values)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var ctx = context.Background()
|
|
var client *redis.Client
|
|
|
|
func InitRedisQueue() {
|
|
// var cancel context.CancelFunc
|
|
// ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
|
|
// defer cancel()
|
|
client = redisdb.RDB("")
|
|
}
|
|
|
|
func CloseRedisQueue() {
|
|
if err := client.Close(); err != nil {
|
|
log.Errorf("redis db close: %s", err)
|
|
}
|
|
}
|