Search code examples
redispublish-subscribe

I have a question about the Pub/Sub structure of Redis


I have three questions about the Pub/Sub structure of redis.

In the pub/sub structure of Redis:

  1. Is it possible to retain published data instead of sending it immediately?
  2. Can required data be directly retrieved and deleted?
  3. Can data be sent when it reaches its expiration time?

Thank you in advance for your response.

I want to a resolution of this problem.

I use the redis like a queue as you know.

I hope the message is not lost and remains intact.


Solution

  • Pub/Sub in Redis isn't a data structure. It merely a mechanism that takes messages that are published and forwards them to subscribers. Nothing is stored.

    You might want to take a look at the Stream data structure in Redis if you want something with a bit more persistence. It's a big topic, but the short version is that you can add events, represented as a series of key-value pairs, to the end of a stream of such events. They're stored in chronological order and you can sit at the end of the stream and process events as they come in, replay the entire history, and all sorts of stuff.

    The basic commands are:

    • XADD adds a new entry to a stream.
    • XREAD reads one or more entries, starting immediately after a given position and moving forward in time to the end of the stream.

    They work like this. First, add a couple events:

    127.0.0.1:6379> XADD my:stream * field1 foo field2 bar
    "1710249632182-0"
    127.0.0.1:6379> XADD my:stream * field1 baz field2 qux
    "1710249683680-0"
    

    Then read them, returning everything after a particular ID:

    127.0.0.1:6379> XREAD STREAMS my:stream 0-0
    1) 1) "foo"
       2) 1) 1) "1710249632182-0"
             2) 1) "field1"
                2) "foo"
                3) "field2"
                4) "bar"
          2) 1) "1710249683680-0"
             2) 1) "field1"
                2) "baz"
                3) "field2"
                4) "qux"
    127.0.0.1:6379> XREAD STREAMS my:stream 1710249632182-0
    1) 1) "foo"
       2) 1) 1) "1710249683680-0"
             2) 1) "field1"
                2) "baz"
                3) "field2"
                4) "qux"
    

    Streams, like I said, are a big topic, but this should help get ya started!