Go整合Redis2.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
}
到此这篇关于Go整合Redis2.0发布订阅的实现的文章就介绍到这了,更多相关Go Redis发布订阅内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
