コード例 #1
0
    def handle_stream(self, stream, address):
        magic_number = yield stream.read_bytes(2)
        # gen_log.info('receive magic number success')
        if magic_number != '\xab\xcd':
            return
        interface_len = yield stream.read_bytes(4)
        interface_len = bytes2int(interface_len)
        gen_log.info('interface len: %d', interface_len)
        interface = yield stream.read_bytes(interface_len)
        gen_log.info('get interface: [%s]', interface)
        method_len = yield stream.read_bytes(4)
        method_len = bytes2int(method_len)
        method = yield stream.read_bytes(method_len)
        pts_len = yield stream.read_bytes(4)
        pts_len = bytes2int(pts_len)
        pts = yield stream.read_bytes(pts_len)
        channel_key = (interface, method, pts)
        gen_log.info('get method: [%s]', method)
        gen_log.info('get pts: [%s]', pts)
        if channel_key in self.dubbo_channel_map:
            dubbo_client = self.dubbo_channel_map[channel_key]
        else:
            dubbo_client = DubboClient('localhost', 20880)
            self.dubbo_channel_map[channel_key] = dubbo_client

        def make_request(Id):
            ar = ActRequest()
            ar.interface = interface
            ar.method = method
            ar.parameter_types_string = pts
            ar.Id = Id
            return ar

        def make_dubbo_request(act_request):
            dr = DubboRequest()
            dr.Id = act_request.Id
            # dr.Id = random.randint(1, 2100000000)
            dr.interface_name = act_request.interface
            dr.method_name = act_request.method
            # dr.dubbo_version = ''
            # dr.version = ''
            dr.args = act_request.parameter
            return dr

        def make_act_response(dubbo_response):
            aresp = ActResponse()
            aresp.Id = dubbo_response.Id
            aresp.result = dubbo_response.result
            return aresp

        while True:
            try:
                Id = yield stream.read_bytes(4)
                request = make_request(bytes2int(Id))
                p_len = yield stream.read_bytes(4)
                request.parameter = yield stream.read_bytes(bytes2int(p_len))
                gen_log.info("get request %d %s", request.Id, request.parameter)

                def callback(dubbo_response):
                    # gen_log.info("get dubbo_resp %d [%s] \nstream write act resp", dubbo_response.Id, dubbo_response.result)
                    stream.write(make_act_response(dubbo_response).encode_body())

                dubbo_client.fetch(make_dubbo_request(request), callback=callback)
            except StreamClosedError:
                break