Redis-xadd和xread的Python示例

时间:2019-03-06 09:09:21

标签: python python-3.x redis

您能否举一个在Python中使用Redis的xreadxadd的非常简单的示例(它显示了xread和xadd输入的返回值的类型和格式)?我已经阅读了许多文档,但是都没有使用Python。

Redis doc给出了一个示例:

> XADD mystream * sensor-id 1234 temperature 19.8
1518951480106-0

但是如果我尝试使用python:

sample = {b"hello":b"12"}
id = r.xadd("mystream", sample)

我收到此错误:

redis.exceptions.ResponseError: WRONGTYPE Operation against a key holding the wrong kind of value

3 个答案:

答案 0 :(得分:1)

查看功能的帮助(或文档字符串(1)(2)),它们非常简单:

>>> import redis
>>> r = redis.Redis()
>>> help(r.xadd)
    xadd(name, fields, id='*', maxlen=None, approximate=True)

    Add to a stream.
    name: name of the stream
    fields: dict of field/value pairs to insert into the stream
    id: Location to insert this record. By default it is appended.
    maxlen: truncate old stream members beyond this size
    approximate: actual stream length may be slightly more than maxlen

>>> help(r.xread)
    xread(streams, count=None, block=None)

    Block and monitor multiple streams for new data.
    streams: a dict of stream names to stream IDs, where
               IDs indicate the last ID already seen.
    count: if set, only return this many items, beginning with the
           earliest available.
    block: number of milliseconds to wait, if nothing already present.

答案 1 :(得分:1)

请确保在运行前先刷新,以确保不存在具有相同名称的列表/流。 :

redis-cli flushall
if __name__ == '__main__':
    r = redis.Redis(host='localhost', port=6379, db=0)
    encoder = JSONEncoder()
    sample = {"hello": encoder.encode([1234,125, 1235, 1235])} # converts list to string
    stream_name = 'mystream'

    for i in range(10):
        r.xadd(stream_name, sample)

    # "$" doesn't seem to work in python
    read_samples = r.xread({stream_name:b"0-0"})

答案 2 :(得分:1)

基于redis-py documentation

Redis初始化:

redis = redis.Redis(host='localhost')

要添加键值对(键值应为字典):

redis.xadd(stream_name, {key: value})

阻止阅读:

redis.xread({stream_name: '$'}, None, 0)
  1. stream_name和ID应该是字典。
  2. $表示最新消息。
  

此外,我没有为流mystream传递常规ID   通过了特殊ID $。这个特殊的ID表示XREAD应该使用   作为最后一个ID,已经存储在流mystream中的最大ID,因此   从我们开始的时间开始,我们将只收到新消息   开始听。from here

  1. 如果您想接收最新消息,而不仅仅是收到任何邮件,则COUNT应该为NONE。
  2. BLOCK选项的0表示以0毫秒的超时进行阻塞(表示永不超时)