Python grpc超时机制代码示例

工作中遇到一个问题,上游服务通过grpc调用下游服务,但是由于下游服务负载太高导致上游服务的调用会随机出现超时的情况,但是有一点不太明确:超时之后,下游服务还会继续进行计算么?

于是自己写了一个damon试了一下:

client:

# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The Python implementation of the GRPC helloworld.Greeter client."""

from __future__ import print_function
import logging

import grpc

import helloworld_pb2
import helloworld_pb2_grpc

def run():
  # NOTE(gRPC Python Team): .close() is possible on a channel and should be
  # used in circumstances in which the with statement does not fit the needs
  # of the code.
  with grpc.insecure_channel('localhost:50051') as channel:
    stub = helloworld_pb2_grpc.GreeterStub(channel)
    response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'), timeout=30)
  print("Greeter client received: " + response.message)

if __name__ == '__main__':
  logging.basicConfig()
  run()

server:

# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The Python implementation of the GRPC helloworld.Greeter server."""

from concurrent import futures
import time
import logging

import grpc

import helloworld_pb2
import helloworld_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

class Greeter(helloworld_pb2_grpc.GreeterServicer):

  def SayHello(self, request, context):
  count = 0
  while count < 10:
    print('time:%s' % (time.time()))
    time.sleep(5)
    return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)

def serve():
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
  server.add_insecure_port('[::]:50051')
  server.start()
  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)

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

这两个例子就是在grpc官方提供的python例子上做了一下小的改动,得到的结果是:当client超时报错退出之后,server还是会继续进行计算,直到结束,那如果是这样的话,超时的机制对于server来说是没有作用的,即使client已经不再等待这个结果了,但是server还是会继续计算,浪费server的资源。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Python使用gRPC传输协议教程

    gRPC 简介: gRPC 是一款高性能.开源的 RPC 框架,产自 Google,基于 ProtoBuf 序列化协议进行开发,支持多种语言(Golang.Python.Java等),本篇只介绍 Python 的 gRPC 使用.因为 gRPC 对 HTTP/2 协议的支持使其在 Android.IOS 等客户端后端服务的开发领域具有良好的前景.gRPC 提供了一种简单的方法来定义服务,同时客户端可以充分利用 HTTP2 stream 的特性,从而有助于节省带宽.降低 TCP 的连接次数.节省C

  • python配置grpc环境

    gRPC 的安装: $ pip install grpcio 安装 ProtoBuf 相关的 python 依赖库: $ pip install protobuf 安装 python grpc 的 protobuf 编译工具: $ pip install grpcio-tools 测试 //源码路径 https://github.com/grpc/grpc git clone https://github.com/grpc/grpc cd grpc/examples/python/hellowo

  • 在Python中使用gRPC的方法示例

    本文介绍了在Python中使用gRPC的方法示例,分享给大家,具体如下: 使用Protocol Buffers的跨平台RPC系统. 安装 使用 pip pip install grpcio pip install grpcio-tools googleapis-common-protos gRPC由两个部分构成,grpcio 和 gRPC 工具, 后者是编译 protocol buffer 以及提供生成代码的插件. 使用 编写protocol buffer 使用 gRPC 首先需要做的是设计 p

  • python使用rpc框架gRPC的方法

    概述 gRPC 是谷歌开源的一个rpc(远程程序调用)框架,可以轻松实现跨语言,跨平台编程,其采用gRPC协议(基于HTTP2). rpc: remote procedure call, 翻译过来就是是远程程序调用.具体来说,就是客户端c1需要调用服务器s1上的某个方法(函数),得到相应的返回值并传递给c1. gRPC协议 要说gRPC协议需要先了解HTTP2, 虽然HTTP1.X 协议至今仍是主流协议,但是随着我们对性能要求越来越高,和web规模的不断扩大,HTTP2就应运而生. 在这里,我们

  • python golang中grpc 使用示例代码详解

    python 1.使用前准备,安装这三个库 pip install grpcio pip install protobuf pip install grpcio_tools 2.建立一个proto文件hello.proto // [python quickstart](https://grpc.io/docs/quickstart/python.html#run-a-grpc-application) // python -m grpc_tools.protoc --python_out=. -

  • Python grpc超时机制代码示例

    工作中遇到一个问题,上游服务通过grpc调用下游服务,但是由于下游服务负载太高导致上游服务的调用会随机出现超时的情况,但是有一点不太明确:超时之后,下游服务还会继续进行计算么? 于是自己写了一个damon试了一下: client: # Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file ex

  • Python实现字符串匹配算法代码示例

    字符串匹配存在的问题 Python中在一个长字符串中查找子串是否存在可以用两种方法:一是str的find()函数,find()函数只返回子串匹配到的起始位置,若没有,则返回-1:二是re模块的findall函数,可以返回所有匹配到的子串. 但是如果用findall函数时需要注意字符串中存在的特殊字符 蛮力法字符串匹配: 将模式对准文本的前m(模式长度)个字符,然后从左到右匹配每一对对应的字符,直到全部匹配或遇到一个不匹配的字符.后一种情况下,模式向右移一位. 代码如下: def string_m

  • Python多线程扫描端口代码示例

    本文代码实现Python多线程扫描端口,具体实现代码如下. #coding:utf-8 import socket import thread import time socket.setdefaulttimeout(3) def socket_port(ip,port): try: if port>=65535: print(u"端口扫描结束!") s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)#创建套接字 result=s

  • python删除服务器文件代码示例

    本文主要研究的是Python编程删除服务器文件,具体实现 代码如下. 实例1 #coding:utf-8 import paramiko """ 创建文件 删除文件 root权限 """ ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname="192.168.1.37",po

  • Python语言生成水仙花数代码示例

    水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身. 本文将通过Python代码实现打印水仙花数,具体如下: #水仙花数 #narcissistic number #水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身. #(例如:1^3 + 5^3+ 3^3 = 153) import math import string for x in range(1,10): a=x*x*x for y in range(0,10

  • python使用邻接矩阵构造图代码示例

    问题 如何使用list构造图 邻接矩阵的方式 Python代码示例 # !/usr/bin/env python # -*-encoding: utf-8-*- # author:LiYanwei # version:0.1 # 邻接矩阵 ''' a---b\ | | \ | | c | | / e---d/ 对于无向图顶点之间存在边,则为1,反之则为0 a b c d e a 0 1 0 0 1 b 1 0 1 1 0 c 0 1 0 1 0 d 0 1 1 0 1 e 1 0 0 1 0 观

  • python切换hosts文件代码示例

    win7以上需要使用管理员权限操作. 复制代码 代码如下: # -*- coding: utf-8 -*-import osimport globimport shutil def format_file_list(files):        all_files_str = ""        for i in range(len(files)):                all_files_str +=  str(i)+":"+files[i]+"

  • Python数据库封装实现代码示例解析

    Django中(原生mysql封装) 1.函数封装 import pymysql # 查 所数据 def get_all(sql): conn = pymysql.connect(host="localhost", user="root", password="root", database="db6") cur = conn.cursor(cursor=pymysql.cursors.DictCursor) cur.exec

  • python shell根据ip获取主机名代码示例

    这篇文章里我们主要分享了python中shell 根据 ip 获取 hostname 或根据 hostname 获取 ip的代码,具体介绍如下. 笔者有时候需要根据hostname获取ip 比如根据machine.company.com 获得ip 10.173.14.117 方法1:利用 socket 模块 里的 gethostbyname 函数 代码如下,使用socket模块 >>> import socket >>> socket.gethostbyname(&qu

  • python脚本设置超时机制系统时间的方法

    本文为大家介绍了python脚本设置系统时间的方法,一共有两种,其一是调用socket直接发送udp包到国家授时中心,其二是调用ntplib包.我在本地电脑ping 国家授时中心地址cn.pool.ntp.org有时出现丢包,然而,二者都没有检查udp是否丢包的机制,方法一在udp丢包后一直处于阻塞状态无法退出,方法二虽然会提示超时,但是不再做其它尝试,比如重新发包,或者向同一个域名的不同IP地址发包.于是,尝试在方法一的代码基础上,增加了超时机制,并且尝试向同一个域名的不同IP地址发包. 具体

随机推荐