Closed4

Redis Pub/Subを学ぶ

o-gao-ga

DockerでRedisを起動する

version: '3'
services:
  redis:
    image: "redis:latest"
    ports:
      - "6379:6379"
    volumes:
      - "./data/redis:/data"
      - "./redis.conf:/etc/redis.conf"
docker compose build
docker compose up

ローカルPCから接続する

redis-cli

Key-Valueをセットする

127.0.0.1:6379 > SET key "value"

Keyをゲットする

127.0.0.1:6379 > GET key
o-gao-ga

RedisでPub/Subをする

Subscribeする

127.0.0.1:6379> SUBSCRIBE [チャネル名]

Publishする

127.0.0.1:6379> PUBLISH [チャネル名] [メッセージ]

実行結果

Subscribe

127.0.0.1:6379> SUBSCRIBE testchannel
1) "subscribe"
2) "testchannel"
3) (integer) 1
1) "message"
2) "testchannel"
3) "test 123"
1) "message"
2) "testchannel"
3) "test 456"
127.0.0.1:6379> 
127.0.0.1:6379> SUBSCRIBE testchannel
1) "message"
2) "testchannel"
3) "test 123"
1) "message"
2) "testchannel"
3) "test 456"
127.0.0.1:6379>

Publish

127.0.0.1:6379> PUBLISH testchannel 'test 123'
(integer) 2
127.0.0.1:6379> PUBLISH testchannel 'test 456'
(integer) 2
127.0.0.1:6379>
o-gao-ga

Go でRedisにアクセスする

package main

import (
	"fmt"

	"github.com/go-redis/redis"
)

func main() {
	client := redis.NewClient(&redis.Options{
        Addr:	  "localhost:6379",
        Password: "", // no password set
        DB:		  0,  // use default DB
    })

	err := client.Set("foo", "bar", 0).Err()
	if err != nil {
		panic(err)
	}

	val, err := client.Get("foo").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println("foo", val)
}
o-gao-ga

Go で Redis で Pub/Subする

package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"time"

	"github.com/go-redis/redis"
)

func main() {
	redisdb := redis.NewClient(&redis.Options{
		Addr:         ":6379",
		DialTimeout:  10 * time.Second,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
		PoolSize:     10,
		PoolTimeout:  30 * time.Second,
	})

	pubsub := redisdb.Subscribe("testchannel")

	// Wait for confirmation that subscription is created before publishing anything.
	_, err := pubsub.Receive()
	if err != nil {
		panic(err)
	}

	// Go channel which receives messages.
	go func(){
		for {
			ch := pubsub.Channel()
			// Consume messages.
			for msg := range ch {
				fmt.Println(msg.Channel, msg.Payload)
			}
		}
	}()

	quit := make(chan os.Signal,1)
	signal.Notify(quit,os.Interrupt)
	<- quit
	log.Printf("chat stopping ...")

	time.AfterFunc(time.Second, func() {
		// When pubsub is closed channel is closed too.
		_ = pubsub.Close()
	})
}

実行結果

Subscribe

gRPC-chat-go $ go run cmd/main.go 
testchannel test iehfwfjewqodjowqef
testchannel test 123445
testchannel test iehfwfjewqodjowqef

Publish

127.0.0.1:6379> PUBLISH testchannel 'test iehfwfjewqodjowqef'
(integer) 1
127.0.0.1:6379> PUBLISH testchannel 'test 123445'
(integer) 1
127.0.0.1:6379> PUBLISH testchannel 'test iehfwfjewqodjowqef'
このスクラップは2024/11/30にクローズされました