grpc的java实现,从无到有

1、Eclipse创建Maven项目

新建一个空的maven工程(不选archetype)。

2、修改POM文件

增加grpc的依赖

        <dependencies>
		<dependency>
			<groupId>io.grpc</groupId>
			<artifactId>grpc-all</artifactId>
			<version>${grpc-version}</version>
		</dependency>
	</dependencies>

增加protocol buffers编译插件项:
	<build>
		<extensions>
			<extension>
				<groupId>kr.motd.maven</groupId>
				<artifactId>os-maven-plugin</artifactId>
				<version>1.4.1.Final</version>
			</extension>
		</extensions>
		<plugins>
			<plugin>
				<groupId>org.xolstice.maven.plugins</groupId>
				<artifactId>protobuf-maven-plugin</artifactId>
				<version>0.5.0</version>
				<configuration>
					<!-- The version of protoc must match protobuf-java. If you don't depend 
						on protobuf-java directly, you will be transitively depending on the protobuf-java 
						version that grpc depends on. -->
					<protocArtifact>com.google.protobuf:protoc:3.0.0-beta-2:exe:${os.detected.classifier}</protocArtifact>
					<pluginId>grpc-java</pluginId>
					<pluginArtifact>io.grpc:protoc-gen-grpc-java:0.14.0:exe:${os.detected.classifier}</pluginArtifact>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>compile</goal>
							<goal>compile-custom</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

其中,上面黄底红字的部分,我们的protoc的版本要和protobuf-Java jar包的版本一致。也就是说我们这里如果写了3.0.0(第一个黄底红字,注:我这里给出的例子使用的是3.0.0-beta-2)

配置文件中给出的
${os.detected.classifier}
在我的机器上被解析为 windows-x86_64 了,这些都是上边的那个扩展插件的作用

3、编写服务.proto文件(hello.proto)

先在src/main目录下新建一个文件夹proto,用来存放我们马上将要创建的proto文件。
syntax = "proto3";

option java_multiple_files = true;
option java_package = "com.jasper.grpc.hello";
option java_outer_classname = "HelloWorldProto";

package helloworld;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

4、编译.proto文件

有两种方式:
1、通过eclipse maven插件进行安装编译  maven install
2、通过protoc.exe执行文件,进行编译(proto和exe文件放在同一目录下)
指令为:protoc --java_out=./dd test.proto   
(不同目录下,例如 protoc --java_out=./src ./msg/hello.proto)


最后,由于生成的代码中有
@java.lang.Override
这种注释,在JDK1.8中有问题,可以修改jdk语言级别为6 或者 直接去掉

5、编写grpc 服务端HelloWorldServer.java

import java.io.IOException;

import com.jasper.grpc.hello.GreeterGrpc;
import com.jasper.grpc.hello.HelloReply;
import com.jasper.grpc.hello.HelloRequest;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

public class HelloWorldServer {

	private int port = 88051;
    private Server server;

    private void start() throws IOException {
        server = ServerBuilder.forPort(port)
                .addService(new GreeterImpl())
                .build()
                .start();

        System.out.println("service start...");

        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {

                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                HelloWorldServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    // block 一直到退出程序 
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }


    public static void main(String[] args) throws IOException, InterruptedException {

        final HelloWorldServer server = new HelloWorldServer();
        server.start();
        server.blockUntilShutdown();
    }


    // 实现 定义一个实现服务接口的类 
    private class GreeterImpl extends GreeterGrpc.AbstractGreeter {


        public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
            System.out.println("service:"+req.getName());
            HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }
	
}

6、编写grpc 客户端 HelloWorldClient.java

import java.util.concurrent.TimeUnit;

import com.jasper.grpc.hello.GreeterGrpc;
import com.jasper.grpc.hello.HelloReply;
import com.jasper.grpc.hello.HelloRequest;

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

public class HelloWorldClient {

	private final ManagedChannel channel; 
    private final GreeterGrpc.GreeterBlockingStub blockingStub; 


    public HelloWorldClient(String host,int port){ 
        channel = ManagedChannelBuilder.forAddress(host,port) 
                .usePlaintext(true) 
                .build();

        blockingStub = GreeterGrpc.newBlockingStub(channel); 
    }


    public void shutdown() throws InterruptedException { 
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); 
    }

    public  void greet(String name){ 
        HelloRequest request = HelloRequest.newBuilder().setName(name).build(); 
        HelloReply   response = blockingStub.sayHello(request);
        System.out.println(response.getMessage());

    }

    public static void main(String[] args) throws InterruptedException { 
        HelloWorldClient client = new HelloWorldClient("127.0.0.1",88051);
        for(int i=0;i<5;i++){
            client.greet("world:"+i);
        }


    }
	
}

参考:http://blog.csdn.net/lyjshen/article/details/52238234#t1
           
           

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章