Conn Object

If you need to implement long connection operations with Redis (such as publish/subscribe), you can use the Conn method to obtain a connection object from the connection pool, and then use that connection object for operations. It’s important to note that when the connection object is no longer in use, it should be explicitly closed by calling the Close method (returned to the connection pool).

Redis - Conn - 图1warning

Since the Conn is a connection object, be aware that it is subject to connection timeout limits, which relate to server configuration.

Publish/Subscribe

You can implement the publish/subscribe pattern through Redis‘s Conn.

  1. package main
  2. import (
  3. "fmt"
  4. _ "github.com/gogf/gf/contrib/nosql/redis/v2"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gctx"
  7. )
  8. func main() {
  9. var (
  10. ctx = gctx.New()
  11. channel = "channel"
  12. )
  13. conn, _ := g.Redis().Conn(ctx)
  14. defer conn.Close(ctx)
  15. _, err := conn.Subscribe(ctx, channel)
  16. if err != nil {
  17. g.Log().Fatal(ctx, err)
  18. }
  19. for {
  20. msg, err := conn.ReceiveMessage(ctx)
  21. if err != nil {
  22. g.Log().Fatal(ctx, err)
  23. }
  24. fmt.Println(msg.Payload)
  25. }
  26. }

After execution, the program will block and wait to receive data.

Open another terminal and use the redis-cli command to enter the Redis Server to publish a message:

  1. $ redis-cli
  2. 127.0.0.1:6379> publish channel test
  3. (integer) 1
  4. 127.0.0.1:6379>

The program terminal will then immediately print the data obtained from the Redis Server: