import redisdef ts_demo():"""时序数据存储RedisTimeSeries测试"""# 连接到Redisr = redis.Redis(host='localhost', password="xxxx", port=63790, db=0)r1 = r.ts()# print(r1.get("ts_key"))# print(r.exists('ts_key'))# # 清空键值# r.delete("ts_key1111")# print(r1.range("ts_key1111", '-', '+'))# 设置过期时间为10s,即timestamp的时间相比当前时间相差10s以上的数据就不存在于这个key中。r1.create(key="ts_key", retention_msecs=10000, duplicate_policy="last")r1.add(key="ts_key1111", timestamp='*', value=1) # *表示取当前时间r1.add(key="ts_key", timestamp='*', value=2)r1.add(key="ts_key", timestamp='*', value=3)r1.add(key="ts_key", timestamp='*', value=4)time.sleep(5)r1.add(key="ts_key", timestamp='*', value=5)r1.add(key="ts_key", timestamp='*', value=6)r1.add(key="ts_key", timestamp='*', value=7)r1.add(key="ts_key", timestamp='*', value=8)r1.add(key="ts_key", timestamp='*', value=9)r1.add(key="ts_key", timestamp='*', value=10)r1.add(key="ts_key", timestamp='*', value=11)print(r1.get("ts_key")) # 获取该key下的时间最大的数据print(r1.range("ts_key", '-', '+')) # 获取该key下的所有数据time.sleep(5)print(r1.range("ts_key", '-', '+')) if __name__ == '__main__':ts_demo()
存在的问题
可能会报错redis没有RedisTimeSeries扩展模块,详细信息可以参考redis官网https://redis.io/docs/latest/develop/data-types/timeseries/
也可以参考如下:
https://blog.csdn.net/LinkSLA/article/details/123040789
查看redis中是否有时间序列数据库模块可以参考如下代码:
# 连接到Redis
r = redis.StrictRedis(host='localhost', password="xxxx", port=63790, db=0)# 获取Redis的信息
info = r.info()
print(info)
# 检查是否加载了时间序列数据库模块
if 'redis_modules' in info and 'name' in info['redis_modules']:for module in info['redis_modules']:if module['name'] == 'timeseries':print("Redis Time Series Database module is enabled.")
else:print("Redis Time Series Database module is not enabled.")