上文讲到SpringPython对Pyro进行了封装,方便用户调用。看看代码:
WebServiceContainer.py
1 from springpython.config import PythonConfig
2 from springpython.config import Object
3 from springpython.remoting.pyro import PyroServiceExporter
4 from springpython.remoting.pyro import PyroProxyFactory
5 from Demo import Echo
6 class WebServiceContainer(PythonConfig):
7 def __init__(self):
8 super(WebServiceContainer,self).__init__()
9
10 @Object(lazy_init=True)
11 def my_web_service(self):
12 service=PyroServiceExporter(
13 service=Echo(),service_name="echo",service_port=9000
14 )
15 return service
16
17 @Object(lazy_init=True)
18 def my_web_client(self):
19 factory=PyroProxyFactory()
20 factory.service_url='PYROLOC://localhost:9000/echo'
21 return factory
WebServiceContainer类继承了SpringPython的PythonConfig,这样WebServiceContainer就拥有了类似Spring的功能,比如可以获得bean。
@Object表示注解,表明其下的方法是一个bean。lazy_init表示延时加载,类似spring。
现在,我们来发布Pyro服务:
WebServer.py
1 #coding=utf-8
2 from springpython.context import ApplicationContext
3 from WebServiceContainer import WebServiceContainer
4 if __name__=='__main__':
5 context=ApplicationContext(WebServiceContainer())
6 #获得bean
7 server=context.get_object("my_web_service")
8 #启动服务
9 server.after_properties_set()
10
11
客户端连接:
WebClient.py
1 #coding=utf-8
2 from springpython.context import ApplicationContext
3 from WebServiceContainer import WebServiceContainer
4 context=ApplicationContext(WebServiceContainer())
5 client=context.get_object("my_web_client")
6 print client.say_hello("zhaolei")
7 print client.say_hello("石头")
一切都很简单,有机会可以看看SpringPython,还是有点意思的。:-)

浙公网安备 33010602011771号