You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.5 KiB
62 lines
1.5 KiB
6 months ago
|
package initialize
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"strconv"
|
||
|
"strings"
|
||
|
"time"
|
||
|
|
||
|
"shop-api/global"
|
||
|
"shop-api/service"
|
||
|
"shop-api/utils"
|
||
|
|
||
|
"github.com/go-redis/redis"
|
||
|
"go.uber.org/zap"
|
||
|
)
|
||
|
|
||
|
func Redis() {
|
||
|
redisCfg := global.MG_CONFIG.Redis
|
||
|
client := redis.NewClient(&redis.Options{
|
||
|
Addr: redisCfg.Addr,
|
||
|
Password: redisCfg.Password, // no password set
|
||
|
DB: redisCfg.DB, // use default DB
|
||
|
})
|
||
|
pong, err := client.Ping().Result()
|
||
|
if err != nil {
|
||
|
global.MG_LOG.Error("redis connect ping failed, err:", zap.Any("err", err))
|
||
|
} else {
|
||
|
global.MG_LOG.Info("redis connect ping response:", zap.String("pong", pong))
|
||
|
global.MG_REDIS = client
|
||
|
}
|
||
|
// 开启过期消息订阅
|
||
|
go PubsunChannel(client)
|
||
|
}
|
||
|
|
||
|
func PubsunChannel(client *redis.Client) {
|
||
|
pubsub := client.Subscribe("__keyevent@" + strconv.Itoa(global.MG_CONFIG.Redis.DB) + "__:expired")
|
||
|
defer pubsub.Close()
|
||
|
for msg := range pubsub.Channel() {
|
||
|
key := strings.Split(msg.Payload, "-")
|
||
|
if len(key) > 1 {
|
||
|
switch key[0] {
|
||
|
case "test":
|
||
|
fmt.Println(key)
|
||
|
case "orderBack":
|
||
|
// 订单超时
|
||
|
err, result := utils.RedisSetNX(key[0]+":"+key[0]+"-"+key[1], "used", 10*time.Second)
|
||
|
if result && err == nil {
|
||
|
go service.UserOrderBack(key[1])
|
||
|
}
|
||
|
case "orderConfirm":
|
||
|
// 订单确认
|
||
|
err, result := utils.RedisSetNX(key[0]+":"+key[0]+"-"+key[1], "used", 10*time.Second)
|
||
|
if result && err == nil {
|
||
|
go service.UserOrderConfirm(key[1])
|
||
|
}
|
||
|
default:
|
||
|
// 默认处理
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|