python学习笔记_week11

时间:2023-03-09 06:09:11
python学习笔记_week11

一、RabbitMQ

python的queue(生产者消费者模型)分为线程queue(不能跨进程)和进程queue(父进程与子进程进行交互或者同属于同一父进程下多个子进程进行交互),那两个独立的进程间的交互(不同程序,python-java,python-php)--(与json,pickle类似)怎么办呢----找个中间代理。比如QQ与Word之间的交互,①可以建立socket通信②通过disk(硬盘)交互---速度慢③找个中间代理broker(也是个独立的程序)---可以为多个程序服务,维护方便(封装好的socket)

安装:RabbitMQ是用erlang语言开发的,所以先安装erlang http://www.erlang.org/downloads,再安装RabbitMQ http://www.rabbitmq.com/install-standalone-mac.html,python中操作RabbitMQ用pika、Celery、Haigha模块

实现最简单的队列通信

python学习笔记_week11

producer

 import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel() #声明一个管道
# 声明queue
channel.queue_declare(queue='hello3')
# n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='',
routing_key='hello3',#queue名字
body='Hello World!')#你的消息内容
print(" [x] Sent 'Hello World!'")
connection.close()

producer

consumer

 import pika,time
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
# You may ask why we declare the queue again ‒ we have already declared it in our previous code.
# We could avoid that if we were sure that the queue already exists. For example if send.py program
# was run before. But we're not yet sure which program to run first. In such cases it's a good
# practice to repeat declaring the queue in both programs.
channel.queue_declare(queue='hello3')
def callback(ch, method, properties, body): #回调函数
print("--->",ch,method,properties) #ch,管道的内存对象地址,method包含你要发消息给谁的信息,一般不用管
time.sleep(30)
print(" [x] Received %r" % body)
ch.basic_ack(delivery_tag=method.delivery_tag)#需要手动确认
channel.basic_consume( #消费消息
callback, #如果收到消息就调用callback函数来处理消息
queue='hello3',
#no_ack=True) #no acknowledgement 不确认,一般不用
)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

consumer

远程连接rabbitmq server的话,需要配置权限 噢 ,首先在rabbitmq server上创建一个用户 sudo rabbitmqctl  add_user alex alex3714 同时还要配置权限,允许从外面访问sudo rabbitmqctl set_permissions -p / alex ".*" ".*" ".*"

set_permissions [-p vhost] {user} {conf} {write} {read}  ----vhost The name of the virtual host to which to grant the user access, defaulting to /.

user The name of the user to grant access to the specified virtual host.

conf A regular expression matching resource names for which the user is granted configure permissions.

write A regular expression matching resource names for which the user is granted write permissions.

read A regular expression matching resource names for which the user is granted read permissions.

客户端连接的时候需要配置认证参数

 credentials = pika.PlainCredentials('alex', 'alex3714')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'10.211.55.5',5672,'/',credentials))
channel = connection.channel()

(一)Work Queues

python学习笔记_week11

在这种模式下,RabbitMQ会默认把p发的消息依次分发给各个消费者(c),跟负载均衡差不多。消息分发轮询,谁先启动,producer先发给谁。

此时,先启动消息生产者,然后再分别启动3个消费者,通过生产者多发送几条消息,你会发现,这几条消息会被依次分配到各个消费者身上  

Doing a task can take a few seconds. You may wonder what happens if one of the consumers starts a long task and dies with it only partly done. With our current code once RabbitMQ delivers message to the customer it immediately removes it from memory. In this case, if you kill a worker we will lose the message it was just processing. We'll also lose all the messages that were dispatched to this particular worker but were not yet handled.

But we don't want to lose any tasks. If a worker dies, we'd like the task to be delivered to another worker.

In order to make sure a message is never lost, RabbitMQ supports message acknowledgments. An ack(nowledgement) is sent back from the consumer to tell RabbitMQ that a particular message had been received, processed and that RabbitMQ is free to delete it.

If a consumer dies (its channel is closed, connection is closed, or TCP connection is lost) without sending an ack, RabbitMQ will understand that a message wasn't processed fully and will re-queue it. If there are other consumers online at the same time, it will then quickly redeliver it to another consumer. That way you can be sure that no message is lost, even if the workers occasionally die.

There aren't any message timeouts; RabbitMQ will redeliver the message when the consumer dies. It's fine even if processing a message takes a very, very long time.

Message acknowledgments are turned on by default. In previous examples we explicitly turned them off via the no_ack=True flag. It's time to remove this flag and send a proper acknowledgment from the worker, once we're done with a task.

Using this code(没有no_ack) we can be sure that even if you kill a worker using CTRL+C while it was processing a message, nothing will be lost. Soon after the worker dies all unacknowledged messages will be redelivered

(二)消息持久化

We have learned how to make sure that even if the consumer dies, the task isn't lost(by default, if wanna disable  use no_ack=True). But our tasks will still be lost if RabbitMQ server stops.

When RabbitMQ quits or crashes it will forget the queues and messages unless you tell it not to. Two things are required to make sure that messages aren't lost: we need to mark both the queue and messages as durable.

First, we need to make sure that RabbitMQ will never lose our queue. In order to do so, we need to declare it as durable:

 channel.queue_declare(queue='hello', durable=True)

Although this command is correct by itself, it won't work in our setup. That's because we've already defined a queue called hello which is not durable. RabbitMQ doesn't allow you to redefine an existing queue with different parameters and will return an error to any program that tries to do that. But there is a quick workaround - let's declare a queue with different name, for exampletask_queue:

 channel.queue_declare(queue='task_queue', durable=True)

This queue_declare change needs to be applied to both the producer and consumer code.

At that point we're sure that the task_queue queue won't be lost even if RabbitMQ restarts. Now we need to mark our messages as persistent - by supplying a delivery_mode property with a value 2.

---durable只是让queue持久化,消息并没有,想让消息持久化,得加上 properties=pika.BasicProperties(delivery_mode = 2, )

 channel.basic_publish(exchange='',
routing_key="task_queue",
body=message,
properties=pika.BasicProperties(
delivery_mode = 2, # make message persistent
))

(三)消息公平分发

如果Rabbit只管按顺序把消息发到各个消费者身上,不考虑消费者负载的话,很可能出现,一个机器配置不高的消费者那里堆积了很多消息处理不完,同时配置高的消费者却一直很轻松。为解决此问题,可以在各个消费者端,配置perfetch=1,意思就是告诉RabbitMQ在我这个消费者当前消息还没处理完的时候就不要再给我发新消息了。

python学习笔记_week11

 def callback(ch, method, properties, body): #回调函数
print("--->",ch,method,properties) #ch,管道的内存对象地址,method包含你要发消息给谁的信息,一般不用管
#time.sleep(30)
print(" [x] Received %r" % body)
ch.basic_ack(delivery_tag=method.delivery_tag)#需要手动确认
channel.basic_qos(prefetch_count=1)
channel.basic_consume( #消费消息
callback, #如果收到消息就调用callback函数来处理消息
queue='hello3',
#no_ack=True) #no acknowledgement 不确认,一般不用
)

(四)Publish\Subscribe(消息发布\订阅)

之前的例子都基本都是1对1的消息发送和接收,即消息只能发送到指定的queue里,但有些时候你想让你的消息被所有的Queue收到,类似广播(收音机)的效果,这时候就要用到exchange了,

An exchange is a very simple thing. On one side it receives messages from producers and the other side it pushes them to queues. The exchange must know exactly what to do with a message it receives. Should it be appended to a particular queue? Should it be appended to many queues? Or should it get discarded. The rules for that are defined by the exchange type.

Exchange在定义的时候是有类型的,以决定到底是哪些Queue符合条件,可以接收消息

fanout: 所有bind到此exchange的queue都可以接收消息  direct: 通过routingKey和exchange决定的那个唯一的queue可以接收消息 topic:所有符合routingKey(此时可以是一个表达式)的routingKey所bind的queue可以接收消息

表达式符号说明:#代表一个或多个字符,*代表任何字符  例:#.a会匹配a.a,aa.a,aaa.a等   *.a会匹配a.a,b.a,c.a等  注:使用RoutingKey为#,Exchange Type为topic的时候相当于使用fanout 

headers: 通过headers 来决定把消息发给哪些queue

python学习笔记_week11

publisher

 import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
exchange_type='fanout')
# message = ' '.join(sys.argv[1:]) or "info: Hello World!"
message ="info: Hello World!"
channel.basic_publish(exchange='logs',
routing_key='',
body=message)
print(" [x] Sent %r" % message)
connection.close()

publisher

subscriber

 import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
exchange_type='fanout')
result = channel.queue_declare(exclusive=True) #exclusive(排他的,唯一的)不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
queue_name = result.method.queue #随机生成的queue名
print("random queue_name:",queue_name)
channel.queue_bind(exchange='logs',
queue=queue_name)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r" % body)
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()

subscriber

注意:广播,是实时的,收不到就没了,消息不会存下来,类似收音机。

(五)有选择的接收消息(exchange type=direct) 

RabbitMQ还支持根据关键字发送,即:队列绑定关键字,发送者将数据根据关键字发送到消息exchange,exchange根据 关键字 判定应该将数据发送至指定队列。

python学习笔记_week11

publisher

 import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
exchange_type='direct')
severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(exchange='direct_logs',
routing_key=severity,
body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()

publisher

subscriber

 import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
exchange_type='direct')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
severities = sys.argv[1:]
if not severities:
sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
sys.exit(1)
print(severities)
for severity in severities:
channel.queue_bind(exchange='direct_logs',
queue=queue_name,
routing_key=severity)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()

subscriber

(六)更细致的消息过滤

Although using the direct exchange improved our system, it still has limitations - it can't do routing based on multiple criteria.

In our logging system we might want to subscribe to not only logs based on severity, but also based on the source which emitted the log. You might know this concept from the syslog unix tool, which routes logs based on both severity (info/warn/crit...) and facility (auth/cron/kern...).

That would give us a lot of flexibility - we may want to listen to just critical errors coming from 'cron' but also all logs from 'kern'.

python学习笔记_week11

publisher

 import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
exchange_type='topic')
routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info' # .info的格式
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(exchange='topic_logs',
routing_key=routing_key,
body=message)
print(" [x] Sent %r:%r" % (routing_key, message))
connection.close()

publisher

subscriber

 import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
exchange_type='topic')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
binding_keys = sys.argv[1:]
if not binding_keys:
sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
sys.exit(1)
for binding_key in binding_keys:
channel.queue_bind(exchange='topic_logs',
queue=queue_name,
routing_key=binding_key) print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()

subscriber

To receive all the logs run:

python receive_logs_topic.py "#"

To receive all logs from the facility "kern":

python receive_logs_topic.py "kern.*"

Or if you want to hear only about "critical" logs:

python receive_logs_topic.py "*.critical"

You can create multiple bindings:

python receive_logs_topic.py "kern.*" "*.critical"

And to emit a log with a routing key "kern.critical" type:

python emit_log_topic.py "kern.critical" "A critical kernel error"

(七)Remote procedure call (RPC)

To illustrate how an RPC service could be used we're going to create a simple client class. It's going to expose a method named call which sends an RPC request and blocks until the answer is received.---snmp也是一种rpc

python学习笔记_week11

server

 import pika
import time
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='rpc_queue')
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
def on_request(ch, method, props, body):
n = int(body)
print(" [.] fib(%s)" % n)
response = fib(n)
ch.basic_publish(exchange='',
routing_key=props.reply_to,#props获取客户端的properties中的reply_to
properties=pika.BasicProperties(correlation_id= \
props.correlation_id),
body=str(response))
ch.basic_ack(delivery_tag=method.delivery_tag) #确保消息消费了
channel.basic_consume(on_request, queue='rpc_queue')
print(" [x] Awaiting RPC requests")
channel.start_consuming()

server

client

 import pika
import uuid,time
class FibonacciRpcClient(object):
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
self.channel = self.connection.channel()
result = self.channel.queue_declare(exclusive=True)
self.callback_queue = result.method.queue
self.channel.basic_consume(self.on_response, #只要一收到消息就调用on_response
no_ack=True,
queue=self.callback_queue)
def on_response(self, ch, method, props, body):
if self.corr_id == props.correlation_id: #确定我发给服务器的命令就是我想要的结果,防止发送多条命令后混乱
self.response = body #收到消息后self.response就不为none了
def call(self, n):
self.response = None
self.corr_id = str(uuid.uuid4()) #随机生成一个确定且唯一的uuid
self.channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
reply_to=self.callback_queue, #让服务器端的消息返回到callback_queue里
correlation_id=self.corr_id,
),
body=str(n)) #发的消息
while self.response is None:
self.connection.process_data_events() #非阻塞(每个一段时间检测一次)版的sart_consuming---收消息用的
print("no msg...")
time.sleep(0.5)
return int(self.response)
fibonacci_rpc = FibonacciRpcClient() #实例化
print(" [x] Requesting fib(6)")
response = fibonacci_rpc.call(6)
print(" [.] Got %r" % response)

client

二、redis

数据传输(1、文件(json,pickle)---效率低;2、socket)

缓存(MongoDB,redis(半持久化,默认存在内存里,但也可改配置存在硬盘),memcached(只能存在内存里),还可以自己写缓存)

python学习笔记_week11   python学习笔记_week11

---name和age是共享的数据,ex代表只存活2s

redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

(一)Redis优点

1.异常快速 : Redis是非常快的,每秒可以执行大约110000设置操作,81000个/每秒的读取操作。

2.支持丰富的数据类型 : Redis支持最大多数开发人员已经知道如列表,集合,可排序集合,哈希等数据类型。这使得在应用中很容易解决的各种问题,因为我们知道哪些问题处理使用哪种数据类型更好解决。

3.操作都是原子的 : 所有 Redis 的操作都是原子,从而确保当两个客户同时访问 Redis 服务器得到的是更新后的值(最新值)。

4.MultiUtility工具:Redis是一个多功能实用工具,可以在很多如:缓存,消息传递队列中使用(Redis原生支持发布/订阅),在应用程序中,如:Web应用程序会话,网站页面点击数等任何短暂的数据;

(二)安装Redis环境

要在 Ubuntu 上安装 Redis,打开终端,然后输入以下命令:
$sudo apt-get update
$sudo apt-get install redis-server
这将在您的计算机上安装Redis

启动 Redis

$redis-server

查看 redis 是否还在运行

$redis-cli
这将打开一个 Redis 提示符,如下图所示:
redis 127.0.0.1:6379>
在上面的提示信息中:127.0.0.1 是本机的IP地址,6379是 Redis 服务器运行的端口。现在输入 PING 命令,如下图所示:
redis 127.0.0.1:6379> ping
PONG
这说明现在你已经成功地在计算机上安装了 Redis。
(三)Python操作Redis
安装redis模块

(四)在Ubuntu上安装Redis桌面管理器

要在Ubuntu 上安装 Redis桌面管理,可以从 http://redisdesktop.com/download 下载包并安装它。Redis 桌面管理器会给你用户界面来管理 Redis 键和数据。

(五)Redis API使用

redis-py 的API的使用可以分类为:1.连接方式 2.连接池 3.操作管道 ①String 操作 ②Hash 操作 ③List 操作 ④Set 操作 ⑤Sort Set 操作 4.管道 5.发布订阅

(六)连接方式

1、操作模式

redis-py提供两个类Redis和StrictRedis用于实现Redis的命令,StrictRedis用于实现大部分官方的命令,并使用官方的语法和命令,Redis是StrictRedis的子类,用于向后兼容旧版本的redis-py。

 import redis
r = redis.Redis(host='10.211.55.4', port=6379)
r.set('foo', 'Bar')
print(r.get("foo")) #bytes类型,python3.x里涉及到socket都是bytes类型

2、连接池redis-py使用connection pool来管理对一个redis server的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池。

 import redis
pool = redis.ConnectionPool(host='192.168.1.1', port=6379)
r = redis.Redis(connection_pool=pool)
r.set('foo', 'Bar')
print(r.get('foo'))

(七)操作

1.String操作

redis中的String在在内存中按照一个name对应一个value来存储。

python学习笔记_week11

①set(name, value, ex=None, px=None, nx=False, xx=False)

在Redis中设置值,默认,不存在则创建,存在则修改。 参数:ex,过期时间(秒),px,过期时间(毫秒)nx,如果设置为True,则只有name不存在时,当前set操作才执行xx,如果设置为True,则只有name存在时,岗前set操作才执行

②setnx(name, value) 设置值,只有name不存在时,执行设置操作(添加)

③setex(name, value, time)  设置值。参数:time,过期时间(数字秒 或 timedelta对象)

④psetex(name, time_ms, value) 设置值。参数:time_ms,过期时间(数字毫秒 或 timedelta对象)

⑤mset(*args, **kwargs )批量设置值。如:mset(k1='v1',k2='v2')mget({'k1':'v1','k2':'v2'})

⑥get(name) 获取值

⑦mget(keys, *args)批量获取如:mget('ylr','wupeiqi')r.mget(['ylr','wupeiqi'])

⑧getset(name, value) 设置新值并获取原来的值

⑨getrange(key, start, end)获取子序列(根据字节获取,非字符)参数:# name,Redis 的 name# start,起始位置(字节)# end,结束位置(字节)# 如: "武沛齐" ,0-3表示 "武",相当于切片

⑩setrange(name, offset, value)# 修改字符串内容,从指定字符串索引开始向后替换(新值太长时,则向后添加)。# 参数:# offset,字符串的索引,字节(一个汉字三个字节)# value,要设置的值

⑪setbit(name, offset, value)

 # 对name对应值的二进制表示的位进行操作
# 参数:
# name,redis的name
# offset,位的索引(将值变换成二进制后再进行索引)
# value,值只能是 1 或 0
# 注:如果在Redis中有一个对应: n1 = "foo",
那么字符串foo的二进制表示为:01100110 01101111 01101111
所以,如果执行 setbit('n1', 7, 1),则就会将第7位设置为1,
那么最终二进制则变成 01100111 01101111 01101111,即:"goo"
# 扩展,转换二进制表示:
# source = "武沛齐"
source = "foo"
for i in source:
num = ord(i) #ord(i)获取在ascii码表的位置,bin(num)转化为二进制
print bin(num).replace('b','')
特别的,如果source是汉字 "武沛齐"怎么办?
答:对于utf-8,每一个汉字占 3 个字节,那么 "武沛齐" 则有 9个字节
对于汉字,for循环时候会按照 字节 迭代,那么在迭代时,将每一个字节转换 十进制数,然后再将十进制数转换成二进制
11100110 10101101 10100110 11100110 10110010 10011011 11101001 10111101 10010000
-------------------------- ----------------------------- -----------------------------
武 沛 齐

用途举例,用最省空间的方式,存储在线用户数及分别是哪些用户在线。新浪微博,几亿用户,MySQL里select大于500万就慢了且占内存较大,所以效率不高。bitcount  显示字符串里有几个1    每登录一个用户将其id(如60)   在字符串n5里setbit 为1(---setbit n5 60 1)   想知道有几个用户 bitcount n5  想知道哪些用户在线循环这个字符串(n5)就可以了 比如getbit n5 60---返回1,代表id为60的这位用户在线,0代表不在线,这样用几十兆(比用MySQL小多了)就能实现该功能。

⑫getbit(name, offset) # 获取name对应的值的二进制表示中的某位的值 (0或1)

⑬bitcount(key, start=None, end=None) # 获取name对应的值的二进制表示中 1 的个数 # 参数:# key,Redis的name  # start,位起始位置  # end,位结束位置

⑭strlen(name) # 返回name对应值的字节长度(一个汉字3个字节)

⑮incr(self, name, amount=1)# 自增 name对应的值,当name不存在时,则创建name=amount,否则,则自增。# 参数:# name,Redis的name# amount,自增数(必须是整数)# 注:同incrby

-----可用来计数在线用户 incr login_users --- 输入一次增加1   离线decr login_users -----输入一次减1

⑯incrbyfloat(self, name, amount=1.0)# 自增 name对应的值,当name不存在时,则创建name=amount,否则,则自增。# 参数:# name,Redis的name # amount,自增数(浮点型)

⑰decr(self, name, amount=1)# 自减 name对应的值,当name不存在时,则创建name=amount,否则,则自减。# 参数:# name,Redis的name # amount,自减数(整数)

⑱append(key, value)# 在redis name对应的值后面追加内容# 参数:key, redis的name  value, 要追加的字符串

2.Hash操作,redis中Hash在内存中的存储格式如下图:

python学习笔记_week11

①hset(name, key, value) # name对应的hash中设置一个键值对(不存在,则创建;否则,修改)# 参数:# name,redis的name # key,name对应的hash中的key # value,name对应的hash中的value # 注:# hsetnx(name, key, value),当name对应的hash中不存在当前key时则创建(相当于添加)

②hmset(name, mapping) # 在name对应的hash中批量设置键值对 # 参数: # name,redis的name # mapping,字典,如:{'k1':'v1', 'k2': 'v2'} # 如:# r.hmset('xx', {'k1':'v1', 'k2': 'v2'})

③hget(name,key) # 在name对应的hash中获取根据key获取value

④hmget(name, keys, *args) # 在name对应的hash中获取多个key的值# 参数:# name,reids对应的name # keys,要获取key集合,如:['k1', 'k2', 'k3'] # *args,要获取的key,如:k1,k2,k3 # 如:# r.mget('xx', ['k1', 'k2']) # 或# print r.hmget('xx', 'k1', 'k2')

⑤hgetall(name) #获取name对应hash的所有键-值

⑥hkeys(name) # 获取name对应的hash中所有的key的值

⑦hvals(name) # 获取name对应的hash中所有的value的值

⑧hexists(name, key) # 检查name对应的hash是否存在当前传入的key

⑨hdel(name,*keys) # 将name对应的hash中指定key的键值对删除

⑩hincrby(name, key, amount=1) # 自增name对应的hash中的指定key的值,不存在则创建key=amount # 参数:# name,redis中的name # key, hash对应的key # amount,自增数(整数)

⑪hincrbyfloat(name, key, amount=1.0) # 自增name对应的hash中的指定key的值,不存在则创建key=amount # 参数:# name,redis中的name # key, hash对应的key # amount,自增数(浮点数) # 自增name对应的hash中的指定key的值,不存在则创建key=amount

⑫hscan(name, cursor=0, match=None, count=None)

Start a full hash scan with:

HSCAN myhash 0

Start a hash scan with fields matching a pattern with:

HSCAN myhash 0 MATCH order_*

Start a hash scan with fields matching a pattern and forcing the scan command to do more scanning with:

HSCAN myhash 0 MATCH order_* COUNT 1000

 # 增量式迭代获取,对于数据大的数据非常有用,hscan可以实现分片的获取数据,并非一次性将数据全部获取完,从而放置内存被撑爆
# 参数:
# name,redis的name
# cursor,游标(基于游标分批取获取数据)
# match,匹配指定key,默认None 表示所有的key
# count,每次分片最少获取个数,默认None表示采用Redis的默认分片个数
# 如:
# 第一次:cursor1, data1 = r.hscan('xx', cursor=0, match=None, count=None)
# 第二次:cursor2, data1 = r.hscan('xx', cursor=cursor1, match=None, count=None)
# ...
# 直到返回值cursor的值为0时,表示数据已经通过分片获取完毕

⑬hscan_iter(name, match=None, count=None)

 # 利用yield封装hscan创建生成器,实现分批去redis中获取数据
# 参数:
# match,匹配指定key,默认None 表示所有的key
# count,每次分片最少获取个数,默认None表示采用Redis的默认分片个数
# 如:
# for item in r.hscan_iter('xx'):
# print item

3. list

List操作,redis中的List在在内存中按照一个name对应一个List来存储。如图:

python学习笔记_week11

①lpush(name,values) # 在name对应的list中添加元素,每个新的元素都添加到列表的最左边 # 如:# r.lpush('oo', 11,22,33) # 保存顺序为: 33,22,11 # 扩展:# rpush(name, values) 表示从右向左操作

②lpushx(name,value) # 在name对应的list中添加元素,只有name已经存在时,值添加到列表的最左边 # 更多:# rpushx(name, value) 表示从右向左操作

③llen(name) # name对应的list元素的个数

④linsert(name, where, refvalue, value)) # 在name对应的列表的某一个值前或后插入一个新值 # 参数:# name,redis的name # where,BEFORE或AFTER # refvalue,标杆值,即:在它前后插入数据 # value,要插入的数据

⑤r.lset(name, index, value) # 对name对应的list中的某一个索引位置重新赋值 # 参数:# name,redis的name # index,list的索引位置 # value,要设置的值

⑥r.lrem(name, value, num) # 在name对应的list中删除指定的值# 参数:# name,redis的name # value,要删除的值 # num,  num=0,删除列表中所有的指定值;# num=2,从前到后,删除2个;# num=-2,从后向前,删除2个

⑦lpop(name) # 在name对应的列表的左侧获取第一个元素并在列表中移除,返回值则是第一个元素 # 更多:# rpop(name) 表示从右向左操作

⑧lindex(name, index) 在name对应的列表中根据索引获取列表元素

⑨lrange(name, start, end) # 在name对应的列表分片获取数据 # 参数:# name,redis的name # start,索引的起始位置 # end,索引结束位置

⑩ltrim(name, start, end) # 在name对应的列表中移除没有在start-end索引之间的值 # 参数:# name,redis的name # start,索引的起始位置 # end,索引结束位置

⑪rpoplpush(src, dst) # 从一个列表取出最右边的元素,同时将其添加至另一个列表的最左边 # 参数:# src,要取数据的列表的name # dst,要添加数据的列表的name

⑫blpop(keys, timeout)  # 将多个列表排列,按照从左到右去pop对应列表的元素 # 参数:# keys,redis的name的集合 # timeout,超时时间,当元素所有列表的元素获取完之后,阻塞等待列表内有数据的时间(秒), 0 表示永远阻塞 # 更多:# r.brpop(keys, timeout),从右向左获取数据

⑬brpoplpush(src, dst, timeout=0) # 从一个列表的右侧移除一个元素并将其添加到另一个列表的左侧 # 参数:# src,取出并要移除元素的列表对应的name# dst,要插入元素的列表对应的name # timeout,当src对应的列表中没有数据时,阻塞等待其有数据的超时时间(秒),0 表示永远阻塞

⑭自定义增量迭代

 # 由于redis类库中没有提供对列表元素的增量迭代,如果想要循环name对应的列表的所有元素,那么就需要:
# 1、获取name对应的所有列表
# 2、循环列表
# 但是,如果列表非常大,那么就有可能在第一步时就将程序的内容撑爆,所有有必要自定义一个增量迭代的功能:
def list_iter(name):
"""
自定义redis列表增量迭代
:param name: redis中的name,即:迭代name对应的列表
:return: yield 返回 列表元素
"""
list_count = r.llen(name)
for index in xrange(list_count):
yield r.lindex(name, index)
# 使用
for item in list_iter('pp'):
print item

4.set集合操作 ----Set操作,Set集合就是不允许重复的列表

①sadd(name,values) # name对应的集合中添加元素

②scard(name) 获取name对应的集合中元素个数

③sdiff(keys, *args) 在第一个name对应的集合中且不在其他name对应的集合的元素集合

④sdiffstore(dest, keys, *args) # 获取第一个name对应的集合中且不在其他name对应的集合,再将其新加入到dest对应的集合中

⑤sinter(keys, *args) # 获取多一个name对应集合的交集

⑥sinterstore(dest, keys, *args) # 获取多一个name对应集合的交集,再讲其加入到dest对应的集合中

⑦sismember(name, value) # 检查value是否是name对应的集合的成员

⑧smembers(name) # 获取name对应的集合的所有成员

⑨smove(src, dst, value) # 将某个成员从一个集合中移动到另外一个集合

⑩spop(name) # 从集合的右侧(尾部)移除一个成员,并将其返回

⑪srandmember(name, numbers) # 从name对应的集合中随机获取 numbers 个元素

⑫srem(name, values) # 在name对应的集合中删除某些值

⑬sunion(keys, *args) # 获取多一个name对应的集合的并集

⑭sunionstore(dest,keys, *args) # 获取多一个name对应的集合的并集,并将结果保存到dest对应的集合中

⑮sscan(name, cursor=0, match=None, count=None)

⑯sscan_iter(name, match=None, count=None) # 同字符串的操作,用于增量迭代分批获取元素,避免内存消耗太大

5.有序集合,在集合的基础上,为每元素排序;元素的排序需要根据另外一个值来进行比较,所以,对于有序集合,每一个元素有两个值,即:值和分数,分数专门用来做排序。

①zadd(name, *args, **kwargs) # 在name对应的有序集合中添加元素如:# zadd('zz', 'n1', 1, 'n2', 2)# 或 # zadd('zz', n1=11, n2=22),命令行中是先分数,后key

②zcard(name) # 获取name对应的有序集合元素的数量

③zcount(name, min, max) # 获取name对应的有序集合中分数 在 [min,max] 之间的个数

④zincrby(name, value, amount) # 自增name对应的有序集合的 name 对应的分数

⑤r.zrange( name, start, end, desc=False, withscores=False, score_cast_func=float)

 # 按照索引范围获取name对应的有序集合的元素
# 参数:
# name,redis的name
# start,有序集合索引起始位置(非分数)
# end,有序集合索引结束位置(非分数)
# desc,排序规则,默认按照分数从小到大排序
# withscores,是否获取元素的分数,默认只获取元素的值
# score_cast_func,对分数进行数据转换的函数
# 更多:
# 从大到小排序
# zrevrange(name, start, end, withscores=False, score_cast_func=float)
# 按照分数范围获取name对应的有序集合的元素
# zrangebyscore(name, min, max, start=None, num=None, withscores=False, score_cast_func=float)
# 从大到小排序
# zrevrangebyscore(name, max, min, start=None, num=None, withscores=False, score_cast_func=float)

⑥zrank(name, value) # 获取某个值在 name对应的有序集合中的排行(从 0 开始)# 更多:# zrevrank(name, value),从大到小排序

⑦zrem(name, values)#  删除name对应的有序集合中值是values的成员 # 如:zrem('zz', ['s1', 's2'])

⑧zremrangebyrank(name, min, max)  # 根据排行范围删除

⑨zremrangebyscore(name, min, max) # 根据分数范围删除

⑩zscore(name, value) # 获取name对应有序集合中 value 对应的分数

⑪zinterstore(dest, keys, aggregate=None) # 获取两个有序集合的交集,按照aggregate进行操作 # aggregate的值为:  SUM  MIN  MAX ---可应用于成绩单不同学科分数及总分

⑫zunionstore(dest, keys, aggregate=None) # 获取两个有序集合的并集,按照aggregate进行操作 # aggregate的值为:  SUM  MIN  MAX

⑬zscan(name, cursor=0, match=None, count=None, score_cast_func=float)

⑭zscan_iter(name, match=None, count=None,score_cast_func=float) # 同字符串相似,相较于字符串新增score_cast_func,用来对分数进行操作

6.其他常用操作

①delete(*names) # 根据删除redis中的任意数据类型

②exists(name) # 检测redis的name是否存在

③keys(pattern='*')

 # 根据模型获取redis的name
# 更多:
# KEYS * 匹配数据库中所有 key 。
# KEYS h?llo 匹配 hello , hallo 和 hxllo 等。
# KEYS h*llo 匹配 hllo 和 heeeeello 等。
# KEYS h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo

④expire(name ,time) # 为某个redis的某个name设置超时时间

⑤rename(src, dst) # 对redis的name重命名为

⑥move(name, db)) # 将redis的某个值移动到指定的db下,该db有该值就不移动,无该值就移动

⑦randomkey() # 随机获取一个redis的name(不删除)

⑧type(name) # 获取name对应值的类型

⑨scan(cursor=0, match=None, count=None)

⑩scan_iter(match=None, count=None) # 同字符串操作,用于增量迭代获取key

(八)管道

redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。

 import redis
pool = redis.ConnectionPool(host='192.168.211.128', port=6379,db=2)
r = redis.Redis(connection_pool=pool)
# pipe = r.pipeline(transaction=False)
pipe = r.pipeline(transaction=True)
pipe.set('name', 'alex')
pipe.set('role', 'dawang')
pipe.execute()

(九)发布订阅

python学习笔记_week11

发布者:服务器

订阅者:Dashboad和数据处理

Demo如下:

 import redis
class RedisHelper:
def __init__(self):
self.__conn = redis.Redis(host='192.168.211.128')
self.chan_sub = 'fm104.5'
self.chan_pub = 'fm104.5'
def public(self, msg):
self.__conn.publish(self.chan_pub, msg)
return True
def subscribe(self):
pub = self.__conn.pubsub() #打开收音机
pub.subscribe(self.chan_sub) #调频道
pub.parse_response() #准备接收,再调用一次才真正接收
return pub

redis_helper

订阅者

 from redis_helper import RedisHelper
obj = RedisHelper()
redis_sub = obj.subscribe()
while True:
msg = redis_sub.parse_response()
print(msg)

redis_sub

发布者

 from redis_helper import RedisHelper
obj = RedisHelper()
obj.public('hello')

redis_pub

更多参考 https://github.com/andymccurdy/redis-py/   http://doc.redisfans.com/

作业:

题目:rpc命令端

需求:

1.可以异步的执行多个命令

2.对多台机器

>>:run "df -h" --hosts 192.168.3.55 10.4.3.4  ---正常的ssh就开始等结果了,但这里要求不阻塞返回task id
task id: 45334
>>: check_task 45334  ---有返回的就返回,要分清两个机器的结果
>>: