Source

starry / README.rst

Starry

Starry 是一个基于zmq的rpc框架。

编写Protobuf定义文件

class Request(messages.Message):
    """Test request message."""
    value = messages.StringField(1)


class Response(messages.Message):
    """Test response message."""
    value = messages.StringField(1)


class SimpleResponse(messages.Message):
    """Simple response message type used for tests."""


class SomeService(remote.Service):

    @remote.method(Request, Response)
    def one_method(self, request):
        raise NotImplement

写一个客户端

建立一个transport:

>>>  transport = TcpTransport(client_id = 'client', # 我的名字
                    address = 'tcp://127.0.0.1:5050',   #  服务端地址
                    service_name = 'some_service',      #  请求的服务名称
                    )
>>>  transport.ping()  # 测试服务器是否还存活着

得到一个Stub:

>>>  stub = SomeService.Stub(transport)

开始调用方法:

>>>  request = Request(value='hello')
>>>  stub.one_method(request)

写一个服务端

建立一个Server:

>>> rpcserver = RPCServer('testserver','tcp://0.0.0.0:5000') # 服务名字,地址

实现一个Service:

>>> class SomeServiceHandler(SomeService):
    ... def one_method(self, request):
    ...     response = Response()
    ...     response.value = request.value
    ...     return response

把Service注册到Server上, 一个Server上可以有多个Service,因此要给每个Service注册一个唯一的名字:

>>> rpcserver.register_service(SomeServiceHandler(),'some_service')

启动server:

>>> rpcserver.start()

但正常情况下,我们的应用启动时要加载自己的配置,这里我们会创建一个Application来托管它:

>>> app = Application(project_path)      #  project_path是项目根路径
>>> app.load_config('etc/config.yaml')   #  相对于project_path的路径
>>> app.add_server(rpc_server)
>>> app.run()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.