Go整合Redis2.0发布订阅

发布于:2025-06-03 ⋅ 阅读:(20) ⋅ 点赞:(0)

Go整合Redis2.0发布订阅


Redis

goredis-cli --version
redis-cli 5.0.14.1 (git:ec77f72d)

Go

go get github.com/go-redis/redis/v8
package redis

import (
    "MyKindom-Server-v2.0/com/xzm/core/config/yaml"
    "MyKindom-Server-v2.0/com/xzm/core/config/yaml/pojo"
    "context"
    "fmt"
    "github.com/go-redis/redis/v8"
    "time"
)

// RDB
var RDB *redis.Client
var globalConfig = yaml.GlobalConfig

// initRedis 初始化Redis连接
func initRedis(config pojo.RedisConfig) error {
    RDB = redis.NewClient(&redis.Options{
        Addr:     config.Address,//Redis地址:localhost:6379
        Password: config.Password,//密码:123456
        DB:       config.DbIndex,//索引 :0
    })

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    // 测试连接
    if err := RDB.Ping(ctx).Err(); err != nil {
        return fmt.Errorf("连接Redis失败: %v", err)
    }

    return nil
}

func init() {
    initRedis(globalConfig.Redis)
}



package main

import (
    "context"
    "fmt"

    "MyKindom-Server-v2.0/com/xzm/core/dadabase/redis"
)

/**
 * @Author: XuZhiMing
 * @Date: 2024/7/18 17:04
 * @Description: 测试redis发布订阅
 */
func main() {

    backgroundCtx := context.Background()
    channelName := "new"
    go subscribeChannel(backgroundCtx, channelName)
    for {
        var message string
        fmt.Print("请输入消息: ")
        fmt.Scanln(&message)
        err := publishMessage(backgroundCtx, channelName, message)
        if err != nil {
            fmt.Println("发布消息失败:", err)
        }
    }
    // 保持程序运行,以便订阅者可以接收到消息
    select {}

}

// 订阅指定频道
func subscribeChannel(ctx context.Context, channel string) {
    pubsub := redis.RDB.Subscribe(ctx, channel)
    defer pubsub.Close()

    fmt.Printf("已订阅频道 [%s]\n", channel)

    // 监听消息
    ch := pubsub.Channel()
    for msg := range ch {
        fmt.Printf("[收到] 频道: %s | 内容: %s\n", msg.Channel, msg.Payload)
    }
}

// 发布消息到指定频道
func publishMessage(ctx context.Context, channel, message string) error {
    err := redis.RDB.Publish(ctx, channel, message).Err()
    if err != nil {
        return err
    }
    fmt.Printf("[发布] 频道: %s | 内容: %s\n", channel, message)
    return nil
}


网站公告

今日签到

点亮在社区的每一天
去签到