使用ProtocolBuffer实现RPC简单示例03

接第01部分,本节用来说明Java语言的代码实现。

使用Protoc.exe生成java代码之后,会生成两个java文件,Client与Server都需要包含这两个文件。

首先是Server端:
1、新建一个java项目,引用以下jar包
protobuf-java-3.0.0-beta-2.jar
grpc-all-0.13.1.jar
guava-18.0.jar
netty-all-4.1.0.CR1.jar
okhttp-2.5.0.jar
okio-1.6.0.jar

2、项目中添加生成的两个java文件。

3、新建一个类MyGRPCServer,实现JustATestGrpc.JustATest接口

package com.neohope.protobuf.grpc.test;

import io.grpc.stub.StreamObserver;

public class MyGRPCServer implements JustATestGrpc.JustATest{

    @Override
    public void add(JustATestOuterClass.AddRequest request, StreamObserver<JustATestOuterClass.AddResponse> responseObserver) {
        JustATestOuterClass.AddResponse rsp =  JustATestOuterClass.AddResponse.newBuilder().setC(request.getA() + request.getB()).build();

        responseObserver.onNext(rsp);
        responseObserver.onCompleted();
    }

    @Override
    public void sayHelloTo(JustATestOuterClass.Person request, StreamObserver<JustATestOuterClass.HelloResponse> responseObserver) {
        JustATestOuterClass.HelloResponse rsp =  JustATestOuterClass.HelloResponse.newBuilder().setRsp("Hello "+ request.getName()).build();

        responseObserver.onNext(rsp);
        responseObserver.onCompleted();
    }
}

4、修改TestServer.java

package com.neohope.protobuf.grpc.test;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.netty.NettyServerBuilder;

import java.io.IOException;
import java.util.Scanner;

public class TestServer {
    public static void main(String[] args) throws IOException {
        Server server = NettyServerBuilder.forPort(1900)
                .addService(JustATestGrpc.bindService(new MyGRPCServer()))
                .build()
                .start();

        Scanner scanner =new Scanner(System.in);
        scanner.nextLine();
    }
}

5、编译运行
然后是Client端:
1、新建一个java项目,引用以下jar包
protobuf-java-3.0.0-beta-2.jar
grpc-all-0.13.1.jar
guava-18.0.jar
netty-all-4.1.0.CR1.jar
okhttp-2.5.0.jar
okio-1.6.0.jar

2、项目中添加生成的两个java文件。

3、修改TestClient.java

package com.neohope.protobuf.grpc.test;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class TestClient {

    public static void main(String[] args)
    {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 1900)
                .usePlaintext(true)
                .build();

        JustATestGrpc.JustATestBlockingStub blockingStub = JustATestGrpc.newBlockingStub(channel);

        JustATestOuterClass.AddRequest areq = JustATestOuterClass.AddRequest.newBuilder().setA(1).setB(2).build();
        JustATestOuterClass.AddResponse arsp = blockingStub.add(areq);
        System.out.println(arsp.getC());

        JustATestOuterClass.Person preq = JustATestOuterClass.Person.newBuilder().setAge(30).setName("neohope").setSex(JustATestOuterClass.Person.SexType.MALE).build();
        JustATestOuterClass.HelloResponse prsp = blockingStub.sayHelloTo(preq);
        System.out.println(prsp.getRsp());

        channel.shutdown();
    }
}

4、编译运行

使用ProtocolBuffer实现RPC简单示例02

接第01部分,本节用来说明C#语言的代码实现。

使用Protoc.exe生成cs代码之后,会生成两个cs文件,Client与Server都需要包含这两个文件。

首先是Server端:
1、新建一个Console项目,引用Protoc程序集中以下几个dll文件,并添加生成的CS文件
Google.Protobuf.dll
Grpc.Core.dll
System.Interactive.Async.dll

2、新建一个类MyGRPCServer,实现JustATest.IJustATest接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Com.Neohope.Protobuf.Grpc.Test;
using Grpc.Core;

namespace TestProtoBufferCliet
{
    class MyGRPCServer : JustATest.IJustATest
    {
        public Task<AddResponse> Add(AddRequest request, ServerCallContext context)
        {
            AddResponse rsp  = new AddResponse();
            rsp.C = request.A + request.B;
            return Task.FromResult(rsp);
        }

        public Task<HelloResponse> SayHelloTo(Person request, ServerCallContext context)
        {
            HelloResponse rsp = new HelloResponse();
            rsp.Rsp = "Hello " + request.Name;
            return Task.FromResult(rsp);
        }
    }
}

3、修改Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.Neohope.Protobuf.Grpc.Test;
using Grpc.Core;
using TestProtoBufferCliet;


namespace TestProtoBuffer
{
    class Program
    {
        static void Main(string[] args)
        {
            Server server = new Server
            {
                Services = { JustATest.BindService(new MyGRPCServer()) },
                Ports = { new ServerPort("localhost", 1900, ServerCredentials.Insecure) }
            };
            server.Start();

            
        }
    }
}

4、编译运行
其中,非托管dll要如下放置

.
│  yourprogram.exe
│  
└─nativelibs
    ├─windows_x64
    │      grpc_csharp_ext.dll
    │      
    └─windows_x86
            grpc_csharp_ext.dll
            

然后是Client端:
1、新建一个Console项目,引用Protoc程序集中以下几个dll文件,并添加生成的CS文件
Google.Protobuf.dll
Grpc.Core.dll
System.Interactive.Async.dll

2、修改Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.Neohope.Protobuf.Grpc.Test;
using Grpc.Core;

namespace TestProtoBufferCliet
{
    class Program
    {
        static void Main(string[] args)
        {
            Channel channel = new Channel("127.0.0.1:1900", ChannelCredentials.Insecure);
            JustATest.JustATestClient client = JustATest.NewClient(channel);

            Person p = new Person();
            p.Name = "neohope";
            p.Age = 30;
            p.Sex = Person.Types.SexType.MALE;
            HelloResponse prsp = client.SayHelloTo(p);
            Console.WriteLine(prsp.Rsp);

            AddRequest areq = new AddRequest();
            areq.A = 1;
            areq.B = 2;
            AddResponse arsp = client.Add(areq);
            Console.WriteLine(arsp.C);

            channel.ShutdownAsync().Wait();
            Console.ReadLine();
        }
    }
}

3、编译运行
其中,非托管dll要如下放置

.
│  yourprogram.exe
│  
└─nativelibs
    ├─windows_x64
    │      grpc_csharp_ext.dll
    │      
    └─windows_x86
            grpc_csharp_ext.dll
            

使用ProtocolBuffer实现RPC简单示例01

ProtocolBuffer大家多是使用其强大的序列化功能。但从3.0版本起,官方提供了GRPC作为其RPC功能的扩展。同样可以用于跨语言RPC通讯了哦。其通信架构如下图所示:

grpc_concept

使用ProtocolBuffer+GRPC的时候,首先要先下载ProtocolBuffer、GRPC,各种语言的编译工具及语言支持包,本例主要用到C#和Java。

ProtoBuffer的编译工具:
protoc.exe
可以到github下载

Java的工具及支持包,都可以到mvnrepository下载到
protobuf-java-3.0.0-beta-2.jar
grpc-all-0.13.1.jar
guava-18.0.jar
netty-all-4.1.0.CR1.jar
okhttp-2.5.0.jar
okio-1.6.0.jar
protoc-gen-grpc-java.exe(protoc-gen-grpc-java-0.13.1-windows-x86_32.exe 或 protoc-gen-grpc-java-0.13.1-windows-x86_64.exe)

C#的工具及支持包,都可以到NuGet上下载到
Google.Protobuf.dll(测试时NuGet没有3.0版本,我从github下源码,把源码从CS6.0人肉降级到CS5.0,用VS2013把编译通过)
Grpc.Core.dll
grpc_csharp_ext.dll(32及64版本)
System.Interactive.Async.dll
grpc_csharp_plugin.exe

使用新版本ProtocolBuffer+GRPC的时候,先定义一个接口描述文件,比如我自己写了一个很简单的接口。
JustATest.proto

syntax = "proto3";

option java_package = "com.neohope.protobuf.grpc.test";

package com.neohope.protobuf.grpc.test;

service JustATest {
  rpc Add (AddRequest) returns (AddResponse){}
  rpc SayHelloTo (Person) returns (HelloResponse);
}

message Person {
  enum SexType {
    MALE = 0;
    FEMALE = 1;
    OTHER = 2;
    UNKNOWN = 4;
  }
  
  string name = 1;
  SexType sex = 2;
  int32 age = 3;
}

message HelloResponse {
  string rsp = 1;
}

message AddRequest {
  int32 a = 1;
  int32 b = 2;
}

message AddResponse {
  int32 c = 1;
}

然后,工具分别编译为java及c#语言

#CS
protoc.exe --plugin=protoc-gen-grpc=grpc_csharp_plugin.exe --grpc_out gen-cs -I. --csharp_out gen-cs JustATest.proto

#Java
protoc.exe --plugin=protoc-gen-grpc=protoc-gen-grpc-java.exe --grpc_out gen-java -I. --java_out gen-java JustATest.proto