gprc 环境搭建 多语言调用

时间:2019-08-25
本文章向大家介绍gprc 环境搭建 多语言调用,主要包括gprc 环境搭建 多语言调用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、golang

1、protocal buffer安装

https://github.com/google/protobuf/releases下载安装包

解压后看到protoc.exe 我这里是windows

最后设置环境变量即可

2、安装 golang protobuf

go get -u github.com/golang/protobuf/proto // golang protobuf 库
go get -u github.com/golang/protobuf/protoc-gen-go //protoc --go_out 工具

3、安装 gRPC-go

go get google.golang.org/grpc

无法下载的话去 https://github.com/grpc/grpc-go 下载

好啦开始写代码,我们就用网上的helloworld来测试

4、项目结构

golang 为服务端,其它语言都为客服端。

helloworld.proto 

syntax = "proto3";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

运行编译命令

protoc --go_out=plugins=grpc:. helloworld.proto

 会生成一个helloworld.pb.go 文件

服务端

package main

import (
	"context"
	"google.golang.org/grpc"
	pb "grpc-test/server/proto/helloworld"
	"log"
	"net"
)

const (
	PORT = ":50001"
)

type server struct {}

func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	log.Println("request: ", in.Name)
	return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

func main(){
	lis, err := net.Listen("tcp", PORT)

	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{})
	log.Println("rpc服务已经开启")
	s.Serve(lis)
}

 客服端

package main

import (
	"context"
	"google.golang.org/grpc"
	pb "grpc-test/client/proto/helloworld"
	"log"
	"os"
)

const (
	address = "localhost:50001"
)

func main() {
	conn, err := grpc.Dial(address, grpc.WithInsecure())

	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}

	defer conn.Close()

	c := pb.NewGreeterClient(conn)

	name := "lin"
	if len(os.Args) > 1 {
		name = os.Args[1]
	}

	r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})

	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}

	log.Println(r.Message)
}

运行结果

二、nodejs

1、这个用npm直接安装 

npm install grpc-tools --save-dev
npm install google-protobuf --save
npm install grpc --save

在./node_modules/grpc-tools/bin下,你会找到 protoc.exe 和 grpc_node_plugin.exe两个文件

2、运行编译命令

./node_modules/grpc-tools/bin/protoc --js_out=import_style=commonjs,binary:./ --plugin=protoc-gen-grpc=./node_modules/grpc-tools/bin/grpc_node_plugin.exe --grpc_out=. helloworld.proto

会生成 helloworld_grpc_pb.js helloworld_pb.js 两个js文件

3、client.js

var grpc = require('grpc');
var messages = require('./proto/helloworld/helloworld_pb.js');
var services = require('./proto/helloworld/helloworld_grpc_pb.js')

var request = new messages.HelloRequest();
request.setName('world');

var client = new services.GreeterClient(
    'localhost:50001',
    grpc.credentials.createInsecure()
);
client.sayHello(request, function(err,data){
    if(err){
        console.error(err);
    }
    console.log(data);
})

4、运行结果

三、C# core

1、安装必要的包

Install-Package Grpc
Install-Package Google.Protobuf
Install-Package Grpc.Tools

2、运行编译命令

protoc.exe -I helloworld --csharp_out helloworld  helloworld/helloworld.proto --grpc_out helloworld --plugin=protoc-gen-grpc=grpc_csharp_plugin.exe

会生成两个文件 Helloworld.cs HelloworldGrpc.cs

3、测试代码

using System;
using Grpc.Core;
using Helloworld;

namespace grpc
{
    class Program
    {
        static void Main(string[] args)
        {
            Channel channel = new Channel("127.0.0.1:50001", ChannelCredentials.Insecure);

            var client = new Greeter.GreeterClient(channel);
            var reply = client.SayHello(new HelloRequest{ Name = "lin" });
            Console.WriteLine("来自" + reply.Message);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("任意键退出...");
            Console.ReadKey();
        }
    }
}

运行结果

好了测试就到这里,因为我这边服务端暂时用到这几种语言。其它语言大家自行测试。

原文地址:https://www.cnblogs.com/fanxp/p/11408114.html