Skip to content

Instantly share code, notes, and snippets.

@AmirSoleimani
Last active December 12, 2018 12:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmirSoleimani/0296d677464f80c6722f6fb022f14b1d to your computer and use it in GitHub Desktop.
Save AmirSoleimani/0296d677464f80c6722f6fb022f14b1d to your computer and use it in GitHub Desktop.
Redis Pub/Sub

Redis Publish/Subscribe Sample

Car: Subscriber

Food: Publisher

package main
import (
"fmt"
"github.com/go-redis/redis"
"github.com/sirupsen/logrus"
)
func main() {
// create redis connection
logrus.Infoln("Redis connection init...")
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
_, err := client.Ping().Result()
if err != nil {
panic(err) // ;)
}
// subscribe `delivery` channel
pubsub := client.Subscribe("foodDelivery")
_, err = pubsub.Receive()
if err != nil {
panic(err)
}
// Go channel which receives messages.
ch := pubsub.Channel()
// Consume messages.
select {
case msg := <-ch:
fmt.Println(msg.Channel, "-> Heyy,", msg.Payload)
pubsub.Close()
}
}
package main
import (
"time"
"github.com/go-redis/redis"
"github.com/sirupsen/logrus"
)
func main() {
// create redis connection
logrus.Infoln("Redis connection init...")
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
_, err := client.Ping().Result()
if err != nil {
panic(err) // ;)
}
// Publish a message after 2 Seconds -> `delivery` channel (demo)
time.AfterFunc(2*time.Second, func() {
err = client.Publish("foodDelivery", "food is ready").Err()
if err != nil {
panic(err)
}
})
// demo...
time.Sleep(3 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment