Openstack 的 RPC使用。

大家都已经很熟悉了RPC了。 比如说nfs就是采用的RPC通信。

尤其SUN RPC 已经成为了C语言开发的经典一种进程间调用机制。

 

openstack 的RPC 机制, 是基于AMQP 活着其他高级消息协议而实现得远程调用机制。

 

而oslo.messaging 在这些消息协议基础上实现了很nice的接口。developer 可以很方便的调用。 

oslo messaging wiki 

 

参考 openstack的developer手册,实现一个RPC 的server端。

http://docs.openstack.org/developer/oslo.messaging/server.html

call_server.py

 1 from oslo_config import cfg
 2 import oslo_messaging
 3 
 4 class ServerControlEndpoint(object):
 5 
 6     target = oslo_messaging.Target(namespace='control',
 7                                    version='2.0')
 8 
 9     def __init__(self, server):
10         print "this is ServerControlEndpoint"
11         self.server = server
12 
13     def stop(self, ctx):
14         if server:
15             self.server.stop()
16 
17 class TestEndpoint(object):
18 
19     def test(self, ctx, arg):
20         print "this is TestEndpoint test server"
21         return arg
22 
23 transport = oslo_messaging.get_transport(cfg.CONF)
24 
25 print "cfg.CONF: ", cfg.CONF
26 print "transport: ", transport
27 target = oslo_messaging.Target(topic='test', server='server1')
28 print "target: ", target
29 endpoints = [
30     ServerControlEndpoint(None),
31     TestEndpoint(),
32 ]
33 server = oslo_messaging.get_rpc_server(transport, target, endpoints,
34                                        executor='blocking')
35 print "server: ", server
36 server.start()
37 server.wait()
View Code

 执行, 等待client 调用。

$ python call_server.py

 

实现一个 RPC的client端

http://docs.openstack.org/developer/oslo.messaging/rpcclient.html

call_client.py

1 from oslo_config import cfg
2 import oslo_messaging as messaging
3 
4 transport = messaging.get_transport(cfg.CONF)
5 target = messaging.Target(topic='test') #, version='2.0')
6 client =  messaging.RPCClient(transport, target)
7 print client.call({}, 'test', arg="hello")
8 cctxt = client.prepare() # version='2.0')
9 print cctxt.call({}, 'test', arg="hello")
View Code

 执行,可以得到 server段的返回结果。 

$ python call_server.py

 

notifier.py

http://docs.openstack.org/developer/oslo.messaging/notifier.html 

 

notification_listener.py

http://docs.openstack.org/developer/oslo.messaging/notification_listener.html

posted @ 2015-05-04 00:44  lvmxh  阅读(698)  评论(0编辑  收藏  举报