关于使用Nginx 代理grpc

5 篇文章 0 订阅
2 篇文章 0 订阅

Nginx从1.13 版本开始支持grpc

  1. http 代理 配置文件修改
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
	worker_connections 768;
	# multi_accept on;
}

http {

	##
	# Basic Settings
	##

	sendfile on;
	tcp_nopush on;
	tcp_nodelay on;
	keepalive_timeout 65;
	types_hash_max_size 2048;
	# server_tokens off;

	# server_names_hash_bucket_size 64;
	# server_name_in_redirect off;

	include /etc/nginx/mime.types;
	default_type application/octet-stream;

	##
	# SSL Settings
	##
  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
                      
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
	ssl_prefer_server_ciphers on;

	access_log /var/log/nginx/access.log;
	error_log /var/log/nginx/error.log;

	gzip on;

	include /etc/nginx/conf.d/*.conf;
	include /etc/nginx/sites-enabled/*;
 
upstream httploadbalance{
	ip_hash;
	server 192.168.1.22:8000 weight=6;
	server 192.168.3.20:80 weight=4;
}
 
 
 
server {
        listen       443 default ssl;
        listen       [::]:443 default ssl;
        server_name  _;

        ssl_certificate  /root/code/djangographql/cert.pem;  
        ssl_certificate_key /root/code/djangographql/key.key;   
        ssl_session_timeout 5m;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;  
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;   
        ssl_prefer_server_ciphers on;

location /api/v1/voucher {
    proxy_pass http://192.168.3.20:80;
}

location /api/v1 {
    proxy_pass http://192.168.1.22:8000;
}

location / {
                proxy_pass http://httploadbalance;    
				proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        }
}


server {
        listen 9999 http2;
 
        access_log /var/log/nginx/grpc_access.log main;
 
        location / {
            # Replace localhost:50051 with the address and port of your gRPC server
            # The 'grpc://' prefix is optional; unencrypted gRPC is the default
            grpc_pass grpc://192.168.1.22:50002;
        }
}

server {
        listen       80 ;
        listen       [::]:80 ;
        server_name  localhost;

location / {
                proxy_pass http://127.0.0.1/pgadmin4/;   
        }
}
}


注意添加log_format main 9999是代理的grpc
python client

channel = grpc.insecure_channel('nginx服务器地址:9999')
  1. https 代理grpc
    生成证书
openssl req -newkey rsa:2048 -nodes -keyout server.key -x509 -days 365 -out server.crt

Nginx 配置

upstream dev {
 server 192.168.1.22:50002;
}
server {
listen 1449 ssl http2;
ssl_certificate /tmp/server.crt;  #Enter you certificate location 
 ssl_certificate_key /tmp/server.key;
location /helloworld.Greeter {
 grpc_pass grpcs://dev;
 }
}

获取代码

#Clone the sample repository 
git clone -b v1.23.0 https://github.com/grpc/grpc
cd examples/python/helloworld
## if you want to make any changes to proto file and regenerate  the stub , go to helloworld directory and run the below command 
python -m grpc_tools.protoc -I../../protos — python_out=. — grpc_python_out=. ../../protos/helloworld.proto

客户端

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.
host = 'localhost'
port = 1449
with open('server.crt', 'rb') as f: # path to you cert location
    trusted_certs = f.read()
credentials = grpc.ssl_channel_credentials(root_certificates=trusted_certs)
 #channel = grpc.secure_channel(‘{}:{}’.format(host, port), credentials)
with grpc.secure_channel('{}:{}'.format(host, port), credentials) as channel:
    stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print('Greeter client received: ' + response.message)
if __name__ == '__main__':
    logging.basicConfig()
    run()

服务端

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):
		return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
	port = '1338'
	with open('server.key', 'rb') as f: #path to you key location 
		private_key = f.read()
	with open('server.crt', 'rb') as f: #path to your cert location
		certificate_chain = f.read()
	server_credentials = grpc.ssl_server_credentials(((private_key, certificate_chain,),))
	server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
	helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
	server.add_secure_port('[::]:'+port, server_credentials)
	 #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()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值