PYTHON/MQ Redis

Source: Internet
Author: User
Tags rabbitmq

Brief introduction

Redis is a cache database, but it is useful not only for databases, but for use as message queues and caches.

As with RABBITMQ, it is also based on socket communication, so be aware that the format of the data is byte.

Basic

Using Redis in Python is quite simple, with Redis modules, and using connection pooling can reduce the overhead of frequent connections.

import redispool = redis.ConnectionPool(host=‘localhost‘, port=6479)cache = redis.Redis(connection_pool=pool)
Operations Common Commands
delete(*names) # 删除任意数据类型exists(name) # 检测是否存在keys(patter=‘*‘) # 根据正则匹配nameexpire(name, time)rename(src, dst)move(name, db) # 将name移到指定dbtype(name)scan(cursor, match=None, count=None)
String

Is the operation of Key-value.

# ex过期时间秒,px过期时间毫秒,nx为True只有name不存在才执行,xxTrue只有name存在才执行set(name, value, ex, px, nx, xx)mset(key, value, key, value...)getset(key, value) # 获取原来的并设置为新的valuegetrange(key, start, end) # 对value切片setbit(key, offset, value) # 对二进制的offset位修改为value值(0/1)bitcount(key) # 计算二进制位1的个数getbit(key, offset) # 获取指定offset位的value状态append(key, value) # 在前value处追加value
Hash

Equivalent to a nested dictionary, key-{key-value}.

# 一个name中可存200多亿个keyhset(name, key, value) # name是hash的key,key和value相当于hash的值hgetall(name) # 获取所有key-valuehget(name, key) # 获取指定valuehkeys(name) # 获取所有keyhvals(name) # 获取所有valuehmset(name, {k1:v1, k2:v2}) # 设置多个hlen(name) # 获取key个数hdel(name, *key) # 删除keyhscan(name, cursor, match=None, count=None) # 从cursor指定的下标开始,匹配match正则,返回列表hscan_iter(name, match=None, count=None) # 返回迭代器
List

is the list, which is evaluated by subscript.

The operation of the Sao is such as Rpoplpush and Blpop.

lpush(name, values) # 从命名列表左侧存入多个值,LIFOrpush(name, values) # 从命名列表右侧存入多个值,FIFOlrange(names, start, end) # 取所有就是0,-1,l代表列表不是左llen(name) # 获取列表长度linsert(name, BEFORE|AFTER, pivot, value) # 在值pivot前后插入新值lset(name, index, value) # 将指定下标的值修改为新值lrem(name, count, value) # 删除指定的值,coutn为0删除所有,正负数代表前后n个lpop(name) # 弹出第一个元素lindex(name, index) # 获取指定index值ltrim(name, start, end) # 移除指定范围外的所有元素rpoplpush(n1, n2)blpop(name, timeout=0) # 0为无限,从name列表左边取值,无值时阻塞指定延迟时间brpop(name, timeout=0)
Set

Equivalent to set, orthogonal, data filtering.

sadd(name, values) # 集合添加值scard(name) # 获取个数sdiff(name, *names) # 差集,去除共有valuessdiffstore(store, name, *names) # 存入storesmembers(name) # 获取所有sinter(name1, name2) # 求交集sismember(name, value) # 检测是否存在smove(name1, name2, value) # 从name1将value移动到name2spop(name) # 尾部弹出srandmembers(name, numbers) # 随机获取指定个数的valuesrem(name, values) # 删除多个valuesunion(name, values) # 并集sscan(name, cursor, match=None, count=None)
Sortset

Ordered set, you can sort elements by weight fraction, and also have the filter characteristics of the set.

zadd(name, *args, **kwargs) # *args为权重-value,**kwargs为value=权重zrange(name, start, end, withscores=False) # 获取指定zcount(name, min, max) # 获取分数在范围内的个数zrank(name, value) # 获取指定value的排名,从0开始zremrangebyrank(name, min, max)zscore(name, value) # 获取分数zscan(name, cursor, match=None, count=None)
Pipe

Pipeline operation, with a certain degree of transaction capability.

pipe = r.pipline(transaction=True)pipe.set(‘name‘, ‘tom‘)time.sleep(30)pipe.set(‘role‘, ‘engineer‘)pipe.execute()
Publish and subscribe mode

Since it is used to deliver messages, there is a publish-and-subscribe pattern, and it is simpler than Rabbitmq,redis's publish and subscribe model.

# 先了解Redis关于发布与订阅模式的几条命令r.publish(channel, message) # 发布消息到指定频道pub = r.pubsub() # 创建订阅对象,通过该对象可订阅频道pub.subscribe(*args, **kwargs) # 订阅一个或多个频道pub.psubscribe(*args, **kwargs) # 订阅模式频道,关键词参数:channel=patternpub.unsubscribe(*args) # 取消订阅,参数为空表示取消所有pub.punsubscribe(*args) # 取消模式订阅

Example:

# 发布者r.publish(channel, message)# 订阅者pub = r.pubsub() # 创建订阅者pub.subscribe(channel) # 订阅频道while True:    for item in pub.listen(): # 循环监听频道消息        print(item[‘channel‘], item[‘message‘])

PYTHON/MQ Redis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.