python中redis使用_redis在python中要怎么用?

去重

def init():

redis_client = redis.Redis()

all_title = {}

redis_client.sadd('news_title',*all_title)

def need_insert_news(news_title):

redis_client = redis.Redis()

if redis_client.sadd('news_title',news_title) == 1:

return True

return False

mongodb批量插入redis持续性数据

import redis

import json

import time

import pymongo

client = redis.Redis()

handler = pymongo.MongoClient().chatper_8.people_info

people_info_list = []

get_count = 0

while True:

people_info_json = client.lpop('people_info')

if people_info_json:

people_info = json.loads(people_info_json.decode())

people_info_list.append(people_info)

if len(people_info_list) >= 1000:

handler.insert_many(people_info_list)

people_info_list = []

else:

if people_info_list and get_count % 1000 == 0:

handler.insert_many(people_info_list)

people_info_list = []

time.sleep(0.1)

get_count += 1

发布/订阅模式实现一对多的消息通信

'''

******************************************************发布/订阅模式实现一对多的消息通信*****

'''

# 向一个频道发布消息

import redis

client = redis.Redis()

client.publish('pubinfo','message')

# 订阅一个频道

listener = client.pubsub()

listener.subscribe('频道名')

for message in listener.listen():

print(message)

# 订阅多个频道

listener = client.pubsub(ignore_subscribe_messages=True) # 生成发布/订阅对象,并且不显示订阅成功信息

listener.subscribe('computer','math','shopping') # 订阅3个频道

for message in listener.listen():

channel = message['channel'].decode()

data = message['data'].decode()

有序集合进行排序

'''

******************************************************有序集合进行排序*****

'''

import redis

client = redis.Redis()

# 向有序集合添加数据

# data = {"xiaohong":32,"xiaoxin":18,"xiaoqiang":24}

client.zadd("age","xiaohong",32,"xiaoxin",18,"xiaoqiang",24)

# 修改有序集合的值

client.zincrby("age","xiaohong",6) # xiaohong增加3岁

# 从小到大排列

# client.zrangebyscore('有序集合名',评分下限,评分上限,结果切片起始位置,结果数量,withscores=False)

# withscores为False,则返回的结果直接是排序好的值。

#withscores为True,则返回的列表里面的元素是元组。

#元组的第一个元素是值,第二个是评分。

value = client.zrangebyscore("age",0,100,withscores=True)

# 结果实例

# [(b'xiaoxin', 18.0), (b'xiaoqiang', 24.0), (b'xiaohong', 38.0)]

# 从大到小排列

# client.zrevrangebyscore('有序集合名',评分上限,评分下限,结果切片起始位置,结果数

#量,withscores=False) # withscores为False,则返回的结果直接是排序好的值。

#withscores为True,则返回的列表里面的元素是元组。

#元组的第一个元素是值,第二个是评分。

value = client.zrevrangebyscore("age",100,0,withscores=False)

# 结果实例

# [b'xiaohong', b'xiaoqiang', b'xiaoxin']

# 查看有序集合有多少个值

value = client.zcard('age')

# 结果实例

# 3

# 在某个评分范围内的值有多少个

value = client.zcount('age', 0, 30)

# 结果实例

# 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值