在 Golang 中使用 Redis 的发布/订阅功能,你可以使用 go-redis
库来实现。以下是如何订阅和发布的基本步骤:
订阅者(Subscriber)
- 连接到 Redis 服务器。
- 使用
Subscribe
方法订阅一个或多个频道。 - 通过返回的
PubSub
对象的Channel
方法获取一个 Go channel。 - 从该 channel 接收消息。
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/go-redis/redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
// 启动订阅者
pubsub := rdb.Subscribe(ctx, "mychannel")
defer pubsub.Close()
ch := pubsub.Channel()
fmt.Println("Subscriber is waiting for messages...")
for {
msg := <-ch
fmt.Printf("Received message from channel %s: %s\n", msg.Channel, msg.Payload)
}
}
发布者(Publisher)
- 连接到 Redis 服务器。
- 使用
Publish
方法向一个频道发布消息。
package main
import (
"context"
"fmt"
"github.com/go-redis/redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
messages := []string{"Hello", "World", "Redis", "PubSub", "Example"}
for _, msg := range messages {
fmt.Printf("Publishing message: %s\n", msg)
err := rdb.Publish(ctx, "mychannel", msg).Err()
if err != nil {
log.Fatalf("Failed to publish message: %v", err)
}
time.Sleep(1 * time.Second) // 等待1秒钟再发布下一个消息
}
fmt.Println("All messages published.")
}
确保在运行这些代码之前,你已经安装了 go-redis
库,可以通过以下命令安装:
go get github.com/go-redis/redis/v9
以上代码示例展示了如何在 Golang 中使用 go-redis
库来实现 Redis 的发布/订阅模式。订阅者会一直等待接收消息,而发布者会向指定频道发送消息。