用Python的gRPC删除Redis数据

需要三个文件:设定文件、服务器程序和客户端程序。

设定文件


syntax = "proto3";

package redis_delete;

service Greeter {
    rpc RedisDelete (RedisRequest) returns (RedisReply) {}
}

message RedisRequest {
    string key = 1;
}

message RedisReply {
    string key = 1;
}

服务器程序

#! /usr/bin/python
#
#   redis_delete_server.py
#
#                   Feb/08/2020
# --------------------------------------------------------------
import sys
import json
import redis
from concurrent import futures
import logging
import  datetime

import grpc

import redis_delete_pb2
import redis_delete_pb2_grpc

# --------------------------------------------------------------
def redis_delete_proc(key_in):
    rr = redis.Redis(host='localhost', port=6379, db=0)
#
    rr.delete(key_in)
#
# --------------------------------------------------------------
class Greeter(redis_delete_pb2_grpc.GreeterServicer):

    def RedisDelete(self, request, context):
        sys.stderr.write("*** RedisRead ***\n")
        sys.stderr.write("*** key = %s ***\n" % request.key)
        redis_delete_proc(request.key)
        return redis_delete_pb2.RedisReply(key=request.key)

# --------------------------------------------------------------
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    redis_delete_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    server.wait_for_termination()

# --------------------------------------------------------------
if __name__ == '__main__':
    logging.basicConfig()
    serve()
# --------------------------------------------------------------

客户端程序

#! /usr/bin/python
#
#   redis_delete_client.py
#
#                   Feb/08/2020
#
# --------------------------------------------------------------
from __future__ import print_function
import logging
import json
import grpc
import sys

import redis_delete_pb2
import redis_delete_pb2_grpc

# --------------------------------------------------------------
def run():
    key_in = sys.argv[1]
#
    with grpc.insecure_channel('localhost:50051') as channel:
        stub = redis_delete_pb2_grpc.GreeterStub(channel)
        response = stub.RedisDelete(redis_delete_pb2.RedisRequest \
            (key=key_in))
        print("Greeter client received aa: " + response.key)
#
# --------------------------------------------------------------
if __name__ == '__main__':
    logging.basicConfig()
    run()
# --------------------------------------------------------------

我将创建 gRPC 的代码。

python -m grpc_tools.protoc -I. \
    --python_out=. \
    --grpc_python_out=. \
    ./redis_delete.proto

服务器程序的启动

./redis_delete_server.py

客户端程序的执行

$ ./redis_delete_client.py t0934
Greeter client received aa: t0934
广告
将在 10 秒后关闭
bannerAds