Python gRPC中的“Connection reset by peer”

3
我们向gRPC服务器发送多个请求。但是偶尔会出现“连接被对等方重置”错误,状态为“UNAVAILABLE”。
GRPC server: NestJS

Client: Python

Python version: 3.8

gRPCio version: 1.50.0

代码:

# Connect to server from client:

def connect_to_user_manager_server() -> AuthorizationControllerStub:
    channel = grpc.insecure_channel(envs.USER_MANAGER_GRPC_URL, options=(
        ('grpc.keepalive_time_ms', 120000),
        ('grpc.keepalive_permit_without_calls', True),
    ))
    stub = AuthorizationControllerStub(channel)

    return stub

client = connect_to_user_manager_server()

user_response = client.CheckAuthorization(authorizationData(authorization=token, requiredRoles=roles))

为了进一步调试此问题,您需要弄清楚为什么连接被对等方重置。一种调试方法是在grpc中启用http和tcp跟踪(GRPC_TRACE=http,tcp和GRPC_VERBOSITY=DEBUG)。查看客户端和服务器的日志可能有助于解释这里发生了什么。 - Yash Tibrewal
1个回答

0

您可以在客户端代码中使用retrying等库添加重试逻辑,也可以手动实现。

例如,您可以使用retrying库来实现重试逻辑:

from retrying import retry

@retry(stop_max_attempt_number=3, wait_fixed=1000)
def connect_to_user_manager_server():
    channel = grpc.insecure_channel(envs.USER_MANAGER_GRPC_URL, options=(
        ('grpc.keepalive_time_ms', 120000),
        ('grpc.keepalive_permit_without_calls', True),
    ))
    stub = AuthorizationControllerStub(channel)
    return stub

这将重试 connect_to_user_manager_server 函数最多3次,每次重试之间延迟1秒。

您也可以手动使用循环和 try-catch 块来实现,如下所示:

attempt = 1
max_attempts = 3
while attempt <= max_attempts:
    try:
        channel = grpc.insecure_channel(envs.USER_MANAGER_GRPC_URL, options=(
            ('grpc.keepalive_time_ms', 120000),
            ('grpc.keepalive_permit_without_calls', True),
        ))
        stub = AuthorizationControllerStub(channel)
        break
    except Exception as e:
        if attempt == max_attempts:
            raise e
        attempt += 1
        time.sleep(1)

这将尝试与服务器建立连接最多3次,每次重试之间延迟1秒。
您可以根据需要调整重试次数和延迟时间。

1
谢谢您的即时回答。我尝试了这个解决方案,但我不确定重试是否是技术上正确的解决方案。 您认为这样做会对服务器造成压力吗? - AminAli
可能会,但你又怎么能够获取你想要的数据呢? - Serge de Gosson de Varennes
我有与服务器端开发人员的联系,他们可以更改服务以修复错误。但是我不知道如何操作。 - AminAli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接