// 变量名:Response // 有一个成员变量,为词典里的值 messageResponse{ string value = 1; }
这个proto文件设置好了之后,通过命令行(cmd,命令提示符,git bash都可以)来调用tool自动生成两个python文件,调用方法为,先进入proto所在的文件夹(例如 cd /i/Github/CDAlter/CDMemory/protos),然后执行如下命令(这里我的proto文件叫作keyvaluestore.proto):
# -*- coding: gbk -*- # ========================================================================== # Copyright (C) since 2020 All rights reserved. # # filename : grpc_server.py # author : chendian / okcd00@qq.com # date : 2020-04-16 # desc : server in grpc service # ========================================================================== import sys import time import grpc from concurrent import futures from multiprocessing import Pool from collections import OrderedDict from grpc._cython.cygrpc import CompressionAlgorithm, CompressionLevel
""" # generate it at first python -m grpc_tools.protoc \ -I ./ \ --python_out=. \ --grpc_python_out=. \ keyvaluestore.proto # then you can get keyvaluestore_pb2_grpc and keyvaluestore_pb2 """ # 这里我的protos不在当前目录下,所以加了个pythonpath sys.path.append('../CDMemory/protos/') from CDMemory.protos import keyvaluestore_pb2_grpc, keyvaluestore_pb2
# -*- coding: gbk -*- # ========================================================================== # Copyright (C) since 2020 All rights reserved. # # filename : grpc_client.py # author : chendian / okcd00@qq.com # date : 2020-04-16 # desc : client in grpc service # ========================================================================== import os import sys if os.environ.get('https_proxy'): del os.environ['https_proxy'] if os.environ.get('http_proxy'): del os.environ['http_proxy'] import grpc
""" # generate it at first python -m grpc_tools.protoc \ -I ./ \ --python_out=. \ --grpc_python_out=. \ keyvaluestore.proto # then you can get keyvaluestore_pb2_grpc and keyvaluestore_pb2 """ # 这里我的protos不在当前目录下,所以加了个pythonpath sys.path.append('../CDMemory/protos/') from CDMemory.protos import keyvaluestore_pb2_grpc, keyvaluestore_pb2
if __name__ == '__main__': # 连接上对应端口的grpc服务 with grpc.insecure_channel('localhost:20416') as channel: # 初始化一个实例作为客户端 stub = keyvaluestore_pb2_grpc.KeyValueStoreStub(channel) # 调用我们定义的remember函数,效果是写入 key=name, value=cd response = stub.remember(keyvaluestore_pb2.Item(key='name', value='cd')) print(response) # value: "Remembered: the value for name is cd" # 调用我们定义的ask函数,效果是查询 key=name 对应的 value response = stub.ask(keyvaluestore_pb2.Key(key='name')) print(response) # value: "cd"