go,redis实现订阅和发布完整实例

作者: adm 分类: go 发布时间: 2023-06-07

1.服务端代码

【备注:这是服务端每秒发送一个数据导发布频道里面】

package main
 
import (
    "fmt"
    "github.com/go-redis/redis"
    "math/rand"
    "time"
)
func main(){
    redisConnect()
}
func redisConnect(){
    server:=redis.NewClient(&redis.Options{
        Addr:"127.0.0.1:6379",
        DB:0,
    })
    for i:=0;i<20;i++ {
        time.Sleep(time.Second)
        rand.Seed(time.Now().Unix())
        num:=rand.Intn(1000)
        n,_:=server.Publish("channel",num).Result()
        fmt.Println(n)
    }
}

2.这是客户端代码

package main
 
import (
    "fmt"
    "github.com/go-redis/redis"
)
 
func main(){
    redisClient()
}
 
func redisClient(){
    client:=redis.NewClient(&redis.Options{
        Addr:"127.0.0.1:6379",
        DB:0,
    })
    pubsub:=client.Subscribe("channel")
    _, err := pubsub.Receive()
            if err != nil {
                
                return
            }
    defer  pubsub.Close()
    for msg:= range pubsub.Channel() {
        fmt.Println(msg.Payload)
    }
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!