Redis Publish Subscribe golang example
In this post we are going to see the example for Redis Publish Subscribe golang example, most of time we use Redis as a cache for key value storage where we can store value against keys for a given time (ttl).
But we can achieve a lot of things using Redis, most of time we use Kafka or other tools for publish subscribe but we can achieve same by using Redis.
What is Publish-subscribe:
From Wikipedia: Publish–subscribe is a communication paradigm in which message senders, known as publishers, do not design messages to be sent directly to specific receivers, known as subscribers, but instead arrange them into classes without knowing the number of subscribers. Subscribers declare their interest in one or more classes, and they only get messages that are relevant to them, regardless of which publications are involved.
To put it another way, Publishers send messages to a queue or topic without knowing who will read them.Subscribers that express an interest in a message subscribe to the subject and consume data from that topic or queue.
Pub/Sub in Redis:
Publish Command: publish <channel> <message>
We use the publish command in Redis using the CLI, which accepts a channel (for publishing) and the message we wish to post.
Subscribe Command: subscribe <channels>
Subscribe command is used to subscribe to one or more channels at once, and it returns message> channel name> message published by publisher> as a response.The fundamental functionality of the Redis pub-sub may be found in the Redis manual, which includes several useful examples.
So now that we've covered the basics or foundations of publish subscribe, let's move on to the code implementation.
Publisher Implementation Using Go:
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/go-redis/redis/v8"
)
var (
ctx = context.Background()
rdb *redis.Client
)
func init() {
rdb = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "yourPassowd", // no password set
DB: 0, // use default DB
})
err := rdb.Ping(ctx).Err()
if nil != err {
log.Fatalf("Errorf: %s", err.Error())
}
}
func publishToRedisChannel() {
var err error
channelName := "first"
for i := 0; i < 10; i++ {
err = rdb.Publish(ctx, channelName, i).Err()
if nil != err {
log.Fatalf("Publish Error: %s", err.Error())
}
time.Sleep(4 * time.Second)
}
}
func main() {
publishToRedisChannel()
fmt.Println("Redis Setup Done")
}
Suscriber Implementation Using Go:
package main
import (
"context"
"fmt"
"log"
"github.com/go-redis/redis/v8"
)
var (
ctx = context.Background()
rdb *redis.Client
)
func init() {
rdb = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "your password", // no password set
DB: 0, // use default DB
})
err := rdb.Ping(ctx).Err()
if nil != err {
log.Fatalf("Errorf: %s", err.Error())
}
}
func subscribeToRedisChannel() {
channelName := "first"
subscriber := rdb.Subscribe(ctx, channelName, "Second")
defer subscriber.Close()
channel := subscriber.Channel()
for msg := range channel {
fmt.Println("received", msg.Payload, "from", msg.Channel)
}
}
func main() {
subscribeToRedisChannel()
fmt.Println("Redis Setup Done")
}
These are examples of single channel-based examples we can subscribe to as many channels through subscribers and read messages based on their incoming.
In the next post, I will give an example of how to subscribe to multiple channels.
Let me know in the comment if you have any questions. Link
0 Comments