Python学习路程day10

时间:2023-02-13 22:38:37

Twsited异步网络框架

Twisted是一个事件驱动的网络框架,其中包含了诸多功能,例如:网络协议、线程、数据库管理、网络操作、电子邮件等。

Python学习路程day10 

事件驱动

简而言之,事件驱动分为二个部分:第一,注册事件;第二,触发事件。

自定义事件驱动框架,命名为:“弑君者”:

 1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 # event_drive.py
5
6 event_list = []
7
8
9 def run():
10 for event in event_list:
11 obj = event()
12 obj.execute()
13
14
15 class BaseHandler(object):
16 """
17 用户必须继承该类,从而规范所有类的方法(类似于接口的功能)
18 """
19 def execute(self):
20 raise Exception('you must overwrite execute')
21
22 最牛逼的事件驱动框架

程序员使用“弑君者框架”:

 1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 from source import event_drive
5
6
7 class MyHandler(event_drive.BaseHandler):
8
9 def execute(self):
10 print 'event-drive execute MyHandler'
11
12
13 event_drive.event_list.append(MyHandler)
14 event_drive.run()

Protocols

Protocols描述了如何以异步的方式处理网络中的事件。HTTP、DNS以及IMAP是应用层协议中的例子。Protocols实现了IProtocol接口,它包含如下的方法:

makeConnection transport对象和服务器之间建立一条连接
connectionMade 连接建立起来后调用
dataReceived 接收数据时调用
connectionLost 关闭连接时调用

Transports

Transports代表网络中两个通信结点之间的连接。Transports负责描述连接的细节,比如连接是面向流式的还是面向数据报的,流控以及可靠性。TCP、UDP和Unix套接字可作为transports的例子。它们被设计为“满足最小功能单元,同时具有最大程度的可复用性”,而且从协议实现中分离出来,这让许多协议可以采用相同类型的传输。Transports实现了ITransports接口,它包含如下的方法:

write 以非阻塞的方式按顺序依次将数据写到物理连接上
writeSequence 将一个字符串列表写到物理连接上
loseConnection 将所有挂起的数据写入,然后关闭连接
getPeer 取得连接中对端的地址信息
getHost 取得连接中本端的地址信息

将transports从协议中分离出来也使得对这两个层次的测试变得更加简单。可以通过简单地写入一个字符串来模拟传输,用这种方式来检查。

 

 

EchoServer

 1 from twisted.internet import protocol
2 from twisted.internet import reactor
3
4 class Echo(protocol.Protocol):
5 def dataReceived(self, data):
6 self.transport.write(data)
7
8 def main():
9 factory = protocol.ServerFactory()
10 factory.protocol = Echo
11
12 reactor.listenTCP(1234,factory)
13 reactor.run()
14
15 if __name__ == '__main__':
16 main()

EchoClient

 1 from twisted.internet import reactor, protocol
2
3
4 # a client protocol
5
6 class EchoClient(protocol.Protocol):
7 """Once connected, send a message, then print the result."""
8
9 def connectionMade(self):
10 self.transport.write("hello alex!")
11
12 def dataReceived(self, data):
13 "As soon as any data is received, write it back."
14 print "Server said:", data
15 self.transport.loseConnection()
16
17 def connectionLost(self, reason):
18 print "connection lost"
19
20 class EchoFactory(protocol.ClientFactory):
21 protocol = EchoClient
22
23 def clientConnectionFailed(self, connector, reason):
24 print "Connection failed - goodbye!"
25 reactor.stop()
26
27 def clientConnectionLost(self, connector, reason):
28 print "Connection lost - goodbye!"
29 reactor.stop()
30
31
32 # this connects the protocol to a server running on port 8000
33 def main():
34 f = EchoFactory()
35 reactor.connectTCP("localhost", 1234, f)
36 reactor.run()
37
38 # this only runs if the module was *not* imported
39 if __name__ == '__main__':
40 main()

运行服务器端脚本将启动一个TCP服务器,监听端口1234上的连接。服务器采用的是Echo协议,数据经TCP transport对象写出。运行客户端脚本将对服务器发起一个TCP连接,回显服务器端的回应然后终止连接并停止reactor事件循环。这里的Factory用来对连接的双方生成protocol对象实例。两端的通信是异步的,connectTCP负责注册回调函数到reactor事件循环中,当socket上有数据可读时通知回调处理。

一个传送文件的例子 

server side 

Python学习路程day10Python学习路程day10
 1 #_*_coding:utf-8_*_
2 # This is the Twisted Fast Poetry Server, version 1.0
3
4 import optparse, os
5
6 from twisted.internet.protocol import ServerFactory, Protocol
7
8
9 def parse_args():
10 usage = """usage: %prog [options] poetry-file
11
12 This is the Fast Poetry Server, Twisted edition.
13 Run it like this:
14
15 python fastpoetry.py <path-to-poetry-file>
16
17 If you are in the base directory of the twisted-intro package,
18 you could run it like this:
19
20 python twisted-server-1/fastpoetry.py poetry/ecstasy.txt
21
22 to serve up John Donne's Ecstasy, which I know you want to do.
23 """
24
25 parser = optparse.OptionParser(usage)
26
27 help = "The port to listen on. Default to a random available port."
28 parser.add_option('--port', type='int', help=help)
29
30 help = "The interface to listen on. Default is localhost."
31 parser.add_option('--iface', help=help, default='localhost')
32
33 options, args = parser.parse_args()
34 print("--arg:",options,args)
35
36 if len(args) != 1:
37 parser.error('Provide exactly one poetry file.')
38
39 poetry_file = args[0]
40
41 if not os.path.exists(args[0]):
42 parser.error('No such file: %s' % poetry_file)
43
44 return options, poetry_file
45
46
47 class PoetryProtocol(Protocol):
48
49 def connectionMade(self):
50 self.transport.write(self.factory.poem)
51 self.transport.loseConnection()
52
53
54 class PoetryFactory(ServerFactory):
55
56 protocol = PoetryProtocol
57
58 def __init__(self, poem):
59 self.poem = poem
60
61
62 def main():
63 options, poetry_file = parse_args()
64
65 poem = open(poetry_file).read()
66
67 factory = PoetryFactory(poem)
68
69 from twisted.internet import reactor
70
71 port = reactor.listenTCP(options.port or 9000, factory,
72 interface=options.iface)
73
74 print 'Serving %s on %s.' % (poetry_file, port.getHost())
75
76 reactor.run()
77
78
79 if __name__ == '__main__':
80 main()
View Code

client side 

Python学习路程day10Python学习路程day10
  1 # This is the Twisted Get Poetry Now! client, version 3.0.
2
3 # NOTE: This should not be used as the basis for production code.
4
5 import optparse
6
7 from twisted.internet.protocol import Protocol, ClientFactory
8
9
10 def parse_args():
11 usage = """usage: %prog [options] [hostname]:port ...
12
13 This is the Get Poetry Now! client, Twisted version 3.0
14 Run it like this:
15
16 python get-poetry-1.py port1 port2 port3 ...
17 """
18
19 parser = optparse.OptionParser(usage)
20
21 _, addresses = parser.parse_args()
22
23 if not addresses:
24 print parser.format_help()
25 parser.exit()
26
27 def parse_address(addr):
28 if ':' not in addr:
29 host = '127.0.0.1'
30 port = addr
31 else:
32 host, port = addr.split(':', 1)
33
34 if not port.isdigit():
35 parser.error('Ports must be integers.')
36
37 return host, int(port)
38
39 return map(parse_address, addresses)
40
41
42 class PoetryProtocol(Protocol):
43
44 poem = ''
45
46 def dataReceived(self, data):
47 self.poem += data
48
49 def connectionLost(self, reason):
50 self.poemReceived(self.poem)
51
52 def poemReceived(self, poem):
53 self.factory.poem_finished(poem)
54
55
56 class PoetryClientFactory(ClientFactory):
57
58 protocol = PoetryProtocol
59
60 def __init__(self, callback):
61 self.callback = callback
62
63 def poem_finished(self, poem):
64 self.callback(poem)
65
66
67 def get_poetry(host, port, callback):
68 """
69 Download a poem from the given host and port and invoke
70
71 callback(poem)
72
73 when the poem is complete.
74 """
75 from twisted.internet import reactor
76 factory = PoetryClientFactory(callback)
77 reactor.connectTCP(host, port, factory)
78
79
80 def poetry_main():
81 addresses = parse_args()
82
83 from twisted.internet import reactor
84
85 poems = []
86
87 def got_poem(poem):
88 poems.append(poem)
89 if len(poems) == len(addresses):
90 reactor.stop()
91
92 for address in addresses:
93 host, port = address
94 get_poetry(host, port, got_poem)
95
96 reactor.run()
97
98 for poem in poems:
99 print poem
100
101
102 if __name__ == '__main__':
103 poetry_main()
View Code

Twisted深入

http://krondo.com/an-introduction-to-asynchronous-programming-and-twisted/ 

http://blog.csdn.net/hanhuili/article/details/9389433 

 

Memcached

Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信。

Memcached安装和基本使用

Memcached安装:

1 wget http://memcached.org/latest
2 tar -zxvf memcached-1.x.x.tar.gz
3 cd memcached-1.x.x
4 ./configure && make && make test && sudo make install
5
6 PS:依赖libevent
7 yum install libevent-devel
8 apt-get install libevent-dev

启动Memcached

 1 memcached -d -m 10    -u root -l 10.211.55.4 -p 12000 -c 256 -P /tmp/memcached.pid
2
3 参数说明:
4 -d 是启动一个守护进程
5 -m 是分配给Memcache使用的内存数量,单位是MB
6 -u 是运行Memcache的用户
7 -l 是监听的服务器IP地址
8 -p 是设置Memcache监听的端口,最好是1024以上的端口
9 -c 选项是最大运行的并发连接数,默认是1024,按照你服务器的负载量来设定
10 -P 是设置保存Memcache的pid文件

Memcached命令

1 存储命令: set/add/replace/append/prepend/cas
2 获取命令: get/gets
3 其他命令: delete/stats..

Python操作Memcached

安装API

1 python操作Memcached使用Python-memcached模块
2 下载安装:https://pypi.python.org/pypi/python-memcached

1、第一次操作

1 import memcache
2
3 mc = memcache.Client(['10.211.55.4:12000'], debug=True)
4 mc.set("foo", "bar")
5 ret = mc.get('foo')
6 print ret

Ps:debug = True 表示运行出现错误时,现实错误信息,上线后移除该参数。

2、天生支持集群

python-memcached模块原生支持集群操作,其原理是在内存维护一个主机列表,且集群中主机的权重值和主机在列表中重复出现的次数成正比

1      主机    权重
2 1.1.1.1 1
3 1.1.1.2 2
4 1.1.1.3 1
5
6 那么在内存中主机列表为:
7 host_list = ["1.1.1.1", "1.1.1.2", "1.1.1.2", "1.1.1.3", ]

如果用户根据如果要在内存中创建一个键值对(如:k1 = "v1"),那么要执行一下步骤:

  • 根据算法将 k1 转换成一个数字
  • 将数字和主机列表长度求余数,得到一个值 N( 0 <= N < 列表长度 )
  • 在主机列表中根据 第2步得到的值为索引获取主机,例如:host_list[N]
  • 连接 将第3步中获取的主机,将 k1 = "v1" 放置在该服务器的内存中

代码实现如下:

1 mc = memcache.Client([('1.1.1.1:12000', 1), ('1.1.1.2:12000', 2), ('1.1.1.3:12000', 1)], debug=True)
2
3 mc.set('k1', 'v1')

3、add
添加一条键值对,如果已经存在的 key,重复执行add操作异常

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 import memcache
4
5 mc = memcache.Client(['10.211.55.4:12000'], debug=True)
6 mc.add('k1', 'v1')
7 # mc.add('k1', 'v2') # 报错,对已经存在的key重复添加,失败!!!

4、replace
replace 修改某个key的值,如果key不存在,则异常

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 import memcache
4
5 mc = memcache.Client(['10.211.55.4:12000'], debug=True)
6 # 如果memcache中存在kkkk,则替换成功,否则一场
7 mc.replace('kkkk','999')

5、set 和 set_multi

set            设置一个键值对,如果key不存在,则创建,如果key存在,则修改
set_multi   设置多个键值对,如果key不存在,则创建,如果key存在,则修改

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 import memcache
4
5 mc = memcache.Client(['10.211.55.4:12000'], debug=True)
6
7 mc.set('key0', 'wupeiqi')
8
9 mc.set_multi({'key1': 'val1', 'key2': 'val2'})

6、delete 和 delete_multi

delete             在Memcached中删除指定的一个键值对
delete_multi    在Memcached中删除指定的多个键值对

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 import memcache
4
5 mc = memcache.Client(['10.211.55.4:12000'], debug=True)
6
7 mc.delete('key0')
8 mc.delete_multi(['key1', 'key2'])

7、get 和 get_multi

get            获取一个键值对
get_multi   获取多一个键值对

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 import memcache
4
5 mc = memcache.Client(['10.211.55.4:12000'], debug=True)
6
7 val = mc.get('key0')
8 item_dict = mc.get_multi(["key1", "key2", "key3"])

8、append 和 prepend

append    修改指定key的值,在该值 后面 追加内容
prepend   修改指定key的值,在该值 前面 插入内容

 1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 import memcache
4
5 mc = memcache.Client(['10.211.55.4:12000'], debug=True)
6 # k1 = "v1"
7
8 mc.append('k1', 'after')
9 # k1 = "v1after"
10
11 mc.prepend('k1', 'before')
12 # k1 = "beforev1after"

9、decr 和 incr  

incr  自增,将Memcached中的某一个值增加 N ( N默认为1 )
decr 自减,将Memcached中的某一个值减少 N ( N默认为1 )

 1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 import memcache
4
5 mc = memcache.Client(['10.211.55.4:12000'], debug=True)
6 mc.set('k1', '777')
7
8 mc.incr('k1')
9 # k1 = 778
10
11 mc.incr('k1', 10)
12 # k1 = 788
13
14 mc.decr('k1')
15 # k1 = 787
16
17 mc.decr('k1', 10)
18 # k1 = 777

10、gets 和 cas

如商城商品剩余个数,假设改值保存在memcache中,product_count = 900
A用户刷新页面从memcache中读取到product_count = 900
B用户刷新页面从memcache中读取到product_count = 900

如果A、B用户均购买商品

A用户修改商品剩余个数 product_count=899
B用户修改商品剩余个数 product_count=899

如此一来缓存内的数据便不在正确,两个用户购买商品后,商品剩余还是 899
如果使用python的set和get来操作以上过程,那么程序就会如上述所示情况!

如果想要避免此情况的发生,只要使用 gets 和 cas 即可,如:

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 import memcache
4 mc = memcache.Client(['10.211.55.4:12000'], debug=True, cache_cas=True)
5
6 v = mc.gets('product_count')
7 # ...
8 # 如果有人在gets之后和cas之前修改了product_count,那么,下面的设置将会执行失败,剖出异常,从而避免非正常数据的产生
9 mc.cas('product_count', "899")

Ps:本质上每次执行gets时,会从memcache中获取一个自增的数字,通过cas去修改gets的值时,会携带之前获取的自增值和memcache中的自增值进行比较,如果相等,则可以提交,如果不想等,那表示在gets和cas执行之间,又有其他人执行了gets(获取了缓冲的指定值), 如此一来有可能出现非正常数据,则不允许修改。

Memcached 真的过时了吗?

 

Redis

 

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

一、Redis安装和基本使用

 1 $ mkdir /usr/local/redis  
2 $ cd /usr/local/src
3 $ wget http://redis.googlecode.com/files/redis-2.6.14.tar.gz
4 $ tar xzf redis-2.6.14.tar.gz
5 $ ln -s redis-2.6.14 redis #建立一个链接
6 $ cd redis
7 $ make PREFIX=/usr/local/redis install #安装到指定目录中
8
9
10 redis启动
11
12 src/redis-server
13
14 redis连接
15
16 src/redis-cli

二、Python操作Redis

1 sudo pip install redis
2 or
3 sudo easy_install redis
4 or
5 源码安装
6
7 详见:https://github.com/WoLpH/redis-py

API使用

redis-py 的API的使用可以分类为:

  • 连接方式
  • 连接池
  • 操作
    • String 操作
    • Hash 操作
    • List 操作
    • Set 操作
    • Sort Set 操作
  • 管道
  • 发布订阅

 

1、操作模式

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

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 import redis
5
6 r = redis.Redis(host='10.211.55.4', port=6379)
7 r.set('foo', 'Bar')
8 print r.get('foo')

2、连接池

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

 1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 import redis
5
6 pool = redis.ConnectionPool(host='10.211.55.4', port=6379)
7
8 r = redis.Redis(connection_pool=pool)
9 r.set('foo', 'Bar')
10 print r.get('foo')

3、操作

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

Python学习路程day10

 

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

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

setnx(name, value)

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

setex(name, value, time)

123 # 设置值# 参数:    # time,过期时间(数字秒 或 timedelta对象)

psetex(name, time_ms, value)

123 # 设置值# 参数:    # time_ms,过期时间(数字毫秒 或 timedelta对象)

mset(*args, **kwargs)

12345 批量设置值如:    mset(k1='v1', k2='v2')        mget({'k1''v1''k2''v2'})

get(name)

1 获取值

mget(keys, *args)

12345 批量获取如:    mget('ylr''wupeiqi')        r.mget(['ylr''wupeiqi'])

getset(name, value)

1 设置新值并获取原来的值

getrange(key, start, end)

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

setrange(name, offset, value)

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

setbit(name, offset, value)

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

getbit(name, offset)

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

bitcount(key, start=None, end=None)

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

bitop(operation, dest, *keys)

12345678910 # 获取多个值,并将值做位运算,将最后的结果保存至新的name对应的值 # 参数:    # operation,AND(并) 、 OR(或) 、 NOT(非) 、 XOR(异或)    # dest, 新的Redis的name    # *keys,要查找的Redis的name # 如:    bitop("AND"'new_name''n1''n2''n3')    # 获取Redis中n1,n2,n3对应的值,然后讲所有的值做位运算(求并集),然后将结果保存 new_name 对应的值中

strlen(name)

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

incr(self, name, amount=1)

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

incrbyfloat(self, name, amount=1.0)

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

decr(self, name, amount=1)

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

append(key, value)

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

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

Python学习路程day10

hset(name, key, value)

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

hmset(name, mapping)

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

hget(name,key)

1 # 在name对应的hash中获取根据key获取value

hmget(name, keys, *args)

1234567891011 # 在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)

1 获取name对应hash的所有键值

hlen(name)

1 # 获取name对应的hash中键值对的个数

hkeys(name)

1 # 获取name对应的hash中所有的key的值

hvals(name)

1 # 获取name对应的hash中所有的value的值

hexists(name, key)

1 # 检查name对应的hash是否存在当前传入的key

hdel(name,*keys)

1 # 将name对应的hash中指定key的键值对删除

hincrby(name, key, amount=1)

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

hincrbyfloat(name, key, amount=1.0)

12345678 # 自增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)

12345678910111213 # 增量式迭代获取,对于数据大的数据非常有用,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)

123456789 # 利用yield封装hscan创建生成器,实现分批去redis中获取数据 # 参数:    # match,匹配指定key,默认None 表示所有的key    # coun

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

Python学习路程day10

lpush(name,values)

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

lpushx(name,value)

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

llen(name)

1 # name对应的list元素的个数

linsert(name, where, refvalue, value))

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

r.lset(name, index, value)

123456 # 对name对应的list中的某一个索引位置重新赋值 # 参数:    # name,redis的name    # index,list的索引位置    # value,要设置的值

r.lrem(name, value, num)

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

lpop(name)

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

lindex(name, index)

1 在name对应的列表中根据索引获取列表元素

lrange(name, start, end)

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

ltrim(name, start, end)

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

rpoplpush(src, dst)

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

blpop(keys, timeout)

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

brpoplpush(src, dst, timeout=0)

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

自定义增量迭代

123456789101112131415161718 # 由于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

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

sadd(name,values)

1 # name对应的集合中添加元素

scard(name)

1 获取name对应的集合中元素个数

sdiff(keys, *args)

1 在第一个name对应的集合中且不在其他name对应的集合的元素集合

sdiffstore(dest, keys, *args)

1 # 获取第一个name对应的集合中且不在其他name对应的集合,再将其新加入到dest对应的集合中

sinter(keys, *args)

1 # 获取多一个name对应集合的并集

sinterstore(dest, keys, *args)

1 # 获取多一个name对应集合的并集,再讲其加入到dest对应的集合中

sismember(name, value)

1 # 检查value是否是name对应的集合的成员

smembers(name)

1 # 获取name对应的集合的所有成员

smove(src, dst, value)

1 # 将某个成员从一个集合中移动到另外一个集合

spop(name)

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

srandmember(name, numbers)

1 # 从name对应的集合中随机获取 numbers 个元素

srem(name, values)

1 # 在name对应的集合中删除某些值

sunion(keys, *args)

1 # 获取多一个name对应的集合的并集

sunionstore(dest,keys, *args)

1 # 获取多一个name对应的集合的并集,并将结果保存到dest对应的集合中

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

1 # 同字符串的操作,用于增量迭代分批获取元素,避免内存消耗太大

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

zadd(name, *args, **kwargs)

12345 # 在name对应的有序集合中添加元素# 如:     # zadd('zz', 'n1', 1, 'n2', 2)     # 或     # zadd('zz', n1=11, n2=22)

zcard(name)

1 # 获取name对应的有序集合元素的数量

zcount(name, min, max)

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

zincrby(name, value, amount)

1 # 自增name对应的有序集合的 name 对应的分数

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

123456789101112131415161718 # 按照索引范围获取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)

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

zrangebylex(name, min, max, start=None, num=None)

1234567891011121314151617 # 当有序集合的所有成员都具有相同的分值时,有序集合的元素会根据成员的 值 (lexicographical ordering)来进行排序,而这个命令则可以返回给定的有序集合键 key 中, 元素的值介于 min 和 max 之间的成员# 对集合中的每个成员进行逐个字节的对比(byte-by-byte compare), 并按照从低到高的顺序, 返回排序后的集合成员。 如果两个字符串有一部分内容是相同的话, 那么命令会认为较长的字符串比较短的字符串要大 # 参数:    # name,redis的name    # min,左区间(值)。 + 表示正无限; - 表示负无限; ( 表示开区间; [ 则表示闭区间    # min,右区间(值)    # start,对结果进行分片处理,索引位置    # num,对结果进行分片处理,索引后面的num个元素 # 如:    # ZADD myzset 0 aa 0 ba 0 ca 0 da 0 ea 0 fa 0 ga    # r.zrangebylex('myzset', "-", "[ca") 结果为:['aa', 'ba', 'ca'] # 更多:    # 从大到小排序    # zrevrangebylex(name, max, min, start=None, num=None)

zrem(name, values)

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

zremrangebyrank(name, min, max)

1 # 根据排行范围删除

zremrangebyscore(name, min, max)

1 # 根据分数范围删除

zremrangebylex(name, min, max)

1 # 根据值返回删除

zscore(name, value)

1 # 获取name对应有序集合中 value 对应的分数

zinterstore(dest, keys, aggregate=None)

12 # 获取两个有序集合的交集,如果遇到相同值不同分数,则按照aggregate进行操作# aggregate的值为:  SUM  MIN  MAX

zunionstore(dest, keys, aggregate=None)

12 # 获取两个有序集合的并集,如果遇到相同值不同分数,则按照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)

1 # 同字符串相似,相较于字符串新增score_cast_func,用来对分数进行操作

其他常用操作

delete(*names)

1 # 根据删除redis中的任意数据类型

exists(name)

1 # 检测redis的name是否存在

keys(pattern='*')

1234567 # 根据模型获取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)

1 # 为某个redis的某个name设置超时时间

rename(src, dst)

1 # 对redis的name重命名为

move(name, db))

1 # 将redis的某个值移动到指定的db下

randomkey()

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

type(name)

1 # 获取name对应值的类型

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

  # 同字符串操作,用于增量迭代获取key

4、管道

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

 1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 import redis
5
6 pool = redis.ConnectionPool(host='10.211.55.4', port=6379)
7
8 r = redis.Redis(connection_pool=pool)
9
10 # pipe = r.pipeline(transaction=False)
11 pipe = r.pipeline(transaction=True)
12
13 r.set('name', 'alex')
14 r.set('role', 'sb')
15
16 pipe.execute()

5、发布订阅

Python学习路程day10

发布者:服务器

订阅者:Dashboad和数据处理

Demo如下:

 1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 import redis
5
6
7 class RedisHelper:
8
9 def __init__(self):
10 self.__conn = redis.Redis(host='10.211.55.4')
11 self.chan_sub = 'fm104.5'
12 self.chan_pub = 'fm104.5'
13
14 def public(self, msg):
15 self.__conn.publish(self.chan_pub, msg)
16 return True
17
18 def subscribe(self):
19 pub = self.__conn.pubsub()
20 pub.subscribe(self.chan_sub)
21 pub.parse_response()
22 return pub

订阅者:

 1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 from monitor.RedisHelper import RedisHelper
5
6 obj = RedisHelper()
7 redis_sub = obj.subscribe()
8
9 while True:
10 msg= redis_sub.parse_response()
11 print msg

发布者:

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 from monitor.RedisHelper import RedisHelper
5
6 obj = RedisHelper()
7 obj.public('hello')

更多参见:https://github.com/andymccurdy/redis-py/

http://doc.redisfans.com/

RabbitMQ

安装 http://www.rabbitmq.com/install-standalone-mac.html

安装python rabbitMQ module 

1 pip install pika
2 or
3 easy_install pika
4 or
5 源码
6
7 https://pypi.python.org/pypi/pika

实现最简单的队列通信

send端

 1 #!/usr/bin/env python
2 import pika
3
4 connection = pika.BlockingConnection(pika.ConnectionParameters(
5 'localhost'))
6 channel = connection.channel()
7
8 #声明queue
9 channel.queue_declare(queue='hello')
10
11 #n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
12 channel.basic_publish(exchange='',
13 routing_key='hello',
14 body='Hello World!')
15 print(" [x] Sent 'Hello World!'")
16 connection.close()

receive端

 1 #_*_coding:utf-8_*_
2 __author__ = 'Alex Li'
3 import pika
4
5 connection = pika.BlockingConnection(pika.ConnectionParameters(
6 'localhost'))
7 channel = connection.channel()
8
9
10 #You may ask why we declare the queue again ‒ we have already declared it in our previous code.
11 # We could avoid that if we were sure that the queue already exists. For example if send.py program
12 #was run before. But we're not yet sure which program to run first. In such cases it's a good
13 # practice to repeat declaring the queue in both programs.
14 channel.queue_declare(queue='hello')
15
16 def callback(ch, method, properties, body):
17 print(" [x] Received %r" % body)
18
19 channel.basic_consume(callback,
20 queue='hello',
21 no_ack=True)
22
23 print(' [*] Waiting for messages. To exit press CTRL+C')
24 channel.start_consuming()

Work Queues

Python学习路程day10

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

消息提供者代码

 1 import pika
2
3 connection = pika.BlockingConnection(pika.ConnectionParameters(
4 'localhost'))
5 channel = connection.channel()
6
7 #声明queue
8 channel.queue_declare(queue='task_queue')
9
10 #n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
11 import sys
12
13 message = ' '.join(sys.argv[1:]) or "Hello World!"
14 channel.basic_publish(exchange='',
15 routing_key='task_queue',
16 body=message,
17 properties=pika.BasicProperties(
18 delivery_mode = 2, # make message persistent
19 ))
20 print(" [x] Sent %r" % message)
21 connection.close()

消费者代码

 1 import pika,time
2
3 connection = pika.BlockingConnection(pika.ConnectionParameters(
4 'localhost'))
5 channel = connection.channel()
6
7
8
9 def callback(ch, method, properties, body):
10 print(" [x] Received %r" % body)
11 time.sleep(body.count(b'.'))
12 print(" [x] Done")
13 ch.basic_ack(delivery_tag = method.delivery_tag)
14
15
16 channel.basic_consume(callback,
17 queue='task_queue',
18 )
19
20 print(' [*] Waiting for messages. To exit press CTRL+C')
21 channel.start_consuming()

Work Queues

Python学习路程day10

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

消息提供者代码

 1 import pika
2
3 connection = pika.BlockingConnection(pika.ConnectionParameters(
4 'localhost'))
5 channel = connection.channel()
6
7 #声明queue
8 channel.queue_declare(queue='task_queue')
9
10 #n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
11 import sys
12
13 message = ' '.join(sys.argv[1:]) or "Hello World!"
14 channel.basic_publish(exchange='',
15 routing_key='task_queue',
16 body=message,
17 properties=pika.BasicProperties(
18 delivery_mode = 2, # make message persistent
19 ))
20 print(" [x] Sent %r" % message)
21 connection.close()

消费者代码

 1 import pika,time
2
3 connection = pika.BlockingConnection(pika.ConnectionParameters(
4 'localhost'))
5 channel = connection.channel()
6
7
8
9 def callback(ch, method, properties, body):
10 print(" [x] Received %r" % body)
11 time.sleep(body.count(b'.'))
12 print(" [x] Done")
13 ch.basic_ack(delivery_tag = method.delivery_tag)
14
15
16 channel.basic_consume(callback,
17 queue='task_queue',
18 )
19
20 print(' [*] Waiting for messages. To exit press CTRL+C')
21 channel.start_consuming()

此时,先启动消息生产者,然后再分别启动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.

1 Vdef callback(ch, method, properties, body):
2 print " [x] Received %r" % (body,)
3 time.sleep( body.count('.') )
4 print " [x] Done"
5 ch.basic_ack(delivery_tag = method.delivery_tag)
6
7 channel.basic_consume(callback,
8 queue='hello')

Using this code 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:

1 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:

1 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.

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

消息公平分发

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

Python学习路程day10

1 channel.basic_qos(prefetch_count=1)

带消息持久化+公平分发的完整代码

生产者端

 1 #!/usr/bin/env python
2 import pika
3 import sys
4
5 connection = pika.BlockingConnection(pika.ConnectionParameters(
6 host='localhost'))
7 channel = connection.channel()
8
9 channel.queue_declare(queue='task_queue', durable=True)
10
11 message = ' '.join(sys.argv[1:]) or "Hello World!"
12 channel.basic_publish(exchange='',
13 routing_key='task_queue',
14 body=message,
15 properties=pika.BasicProperties(
16 delivery_mode = 2, # make message persistent
17 ))
18 print(" [x] Sent %r" % message)
19 connection.close()

消费者端

 1 #!/usr/bin/env python
2 import pika
3 import time
4
5 connection = pika.BlockingConnection(pika.ConnectionParameters(
6 host='localhost'))
7 channel = connection.channel()
8
9 channel.queue_declare(queue='task_queue', durable=True)
10 print(' [*] Waiting for messages. To exit press CTRL+C')
11
12 def callback(ch, method, properties, body):
13 print(" [x] Received %r" % body)
14 time.sleep(body.count(b'.'))
15 print(" [x] Done")
16 ch.basic_ack(delivery_tag = method.delivery_tag)
17
18 channel.basic_qos(prefetch_count=1)
19 channel.basic_consume(callback,
20 queue='task_queue')
21
22 channel.start_consuming()

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学习路程day10

消息publisher

 1 import pika
2 import sys
3
4 connection = pika.BlockingConnection(pika.ConnectionParameters(
5 host='localhost'))
6 channel = connection.channel()
7
8 channel.exchange_declare(exchange='logs',
9 type='fanout')
10
11 message = ' '.join(sys.argv[1:]) or "info: Hello World!"
12 channel.basic_publish(exchange='logs',
13 routing_key='',
14 body=message)
15 print(" [x] Sent %r" % message)
16 connection.close()

消息subscriber

 1 #_*_coding:utf-8_*_
2 __author__ = 'Alex Li'
3 import pika
4
5 connection = pika.BlockingConnection(pika.ConnectionParameters(
6 host='localhost'))
7 channel = connection.channel()
8
9 channel.exchange_declare(exchange='logs',
10 type='fanout')
11
12 result = channel.queue_declare(exclusive=True) #不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
13 queue_name = result.method.queue
14
15 channel.queue_bind(exchange='logs',
16 queue=queue_name)
17
18 print(' [*] Waiting for logs. To exit press CTRL+C')
19
20 def callback(ch, method, properties, body):
21 print(" [x] %r" % body)
22
23 channel.basic_consume(callback,
24 queue=queue_name,
25 no_ack=True)
26
27 channel.start_consuming()

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

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

Python学习路程day10

publisher

 1 import pika
2 import sys
3
4 connection = pika.BlockingConnection(pika.ConnectionParameters(
5 host='localhost'))
6 channel = connection.channel()
7
8 channel.exchange_declare(exchange='direct_logs',
9 type='direct')
10
11 severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
12 message = ' '.join(sys.argv[2:]) or 'Hello World!'
13 channel.basic_publish(exchange='direct_logs',
14 routing_key=severity,
15 body=message)
16 print(" [x] Sent %r:%r" % (severity, message))
17 connection.close()

subscriber

 1 import pika
2 import sys
3
4 connection = pika.BlockingConnection(pika.ConnectionParameters(
5 host='localhost'))
6 channel = connection.channel()
7
8 channel.exchange_declare(exchange='direct_logs',
9 type='direct')
10
11 result = channel.queue_declare(exclusive=True)
12 queue_name = result.method.queue
13
14 severities = sys.argv[1:]
15 if not severities:
16 sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
17 sys.exit(1)
18
19 for severity in severities:
20 channel.queue_bind(exchange='direct_logs',
21 queue=queue_name,
22 routing_key=severity)
23
24 print(' [*] Waiting for logs. To exit press CTRL+C')
25
26 def callback(ch, method, properties, body):
27 print(" [x] %r:%r" % (method.routing_key, body))
28
29 channel.basic_consume(callback,
30 queue=queue_name,
31 no_ack=True)
32
33 channel.start_consuming()

更细致的消息过滤

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学习路程day10

publisher

 1 import pika
2 import sys
3
4 connection = pika.BlockingConnection(pika.ConnectionParameters(
5 host='localhost'))
6 channel = connection.channel()
7
8 channel.exchange_declare(exchange='topic_logs',
9 type='topic')
10
11 routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info'
12 message = ' '.join(sys.argv[2:]) or 'Hello World!'
13 channel.basic_publish(exchange='topic_logs',
14 routing_key=routing_key,
15 body=message)
16 print(" [x] Sent %r:%r" % (routing_key, message))
17 connection.close()

subscriber

 1 import pika
2 import sys
3
4 connection = pika.BlockingConnection(pika.ConnectionParameters(
5 host='localhost'))
6 channel = connection.channel()
7
8 channel.exchange_declare(exchange='topic_logs',
9 type='topic')
10
11 result = channel.queue_declare(exclusive=True)
12 queue_name = result.method.queue
13
14 binding_keys = sys.argv[1:]
15 if not binding_keys:
16 sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
17 sys.exit(1)
18
19 for binding_key in binding_keys:
20 channel.queue_bind(exchange='topic_logs',
21 queue=queue_name,
22 routing_key=binding_key)
23
24 print(' [*] Waiting for logs. To exit press CTRL+C')
25
26 def callback(ch, method, properties, body):
27 print(" [x] %r:%r" % (method.routing_key, body))
28
29 channel.basic_consume(callback,
30 queue=queue_name,
31 no_ack=True)
32
33 channel.start_consuming()

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:

1 fibonacci_rpc = FibonacciRpcClient()
2 result = fibonacci_rpc.call(4)
3 print("fib(4) is %r" % result)

Python学习路程day10

RPC server

Python学习路程day10Python学习路程day10
 1 #_*_coding:utf-8_*_
2 __author__ = 'Alex Li'
3 import pika
4 import time
5 connection = pika.BlockingConnection(pika.ConnectionParameters(
6 host='localhost'))
7
8 channel = connection.channel()
9
10 channel.queue_declare(queue='rpc_queue')
11
12 def fib(n):
13 if n == 0:
14 return 0
15 elif n == 1:
16 return 1
17 else:
18 return fib(n-1) + fib(n-2)
19
20 def on_request(ch, method, props, body):
21 n = int(body)
22
23 print(" [.] fib(%s)" % n)
24 response = fib(n)
25
26 ch.basic_publish(exchange='',
27 routing_key=props.reply_to,
28 properties=pika.BasicProperties(correlation_id = \
29 props.correlation_id),
30 body=str(response))
31 ch.basic_ack(delivery_tag = method.delivery_tag)
32
33 channel.basic_qos(prefetch_count=1)
34 channel.basic_consume(on_request, queue='rpc_queue')
35
36 print(" [x] Awaiting RPC requests")
37 channel.start_consuming()
View Code

RPC client

Python学习路程day10Python学习路程day10
 1 import pika
2 import uuid
3
4 class FibonacciRpcClient(object):
5 def __init__(self):
6 self.connection = pika.BlockingConnection(pika.ConnectionParameters(
7 host='localhost'))
8
9 self.channel = self.connection.channel()
10
11 result = self.channel.queue_declare(exclusive=True)
12 self.callback_queue = result.method.queue
13
14 self.channel.basic_consume(self.on_response, no_ack=True,
15 queue=self.callback_queue)
16
17 def on_response(self, ch, method, props, body):
18 if self.corr_id == props.correlation_id:
19 self.response = body
20
21 def call(self, n):
22 self.response = None
23 self.corr_id = str(uuid.uuid4())
24 self.channel.basic_publish(exchange='',
25 routing_key='rpc_queue',
26 properties=pika.BasicProperties(
27 reply_to = self.callback_queue,
28 correlation_id = self.corr_id,
29 ),
30 body=str(n))
31 while self.response is None:
32 self.connection.process_data_events()
33 return int(self.response)
34
35 fibonacci_rpc = FibonacciRpcClient()
36
37 print(" [x] Requesting fib(30)")
38 response = fibonacci_rpc.call(30)
39 print(" [.] Got %r" % response)
View Code

Memcached & Redis使用 

http://www.cnblogs.com/wupeiqi/articles/5132791.html  

Work Queues

Python学习路程day10

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

消息提供者代码