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
           
           

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