ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

gRPC Java实例

2019-09-11 20:38:25  阅读:16  来源: 互联网

标签:Java protobuf gRPC server grpc 实例 import java com



gRPC Java 实例

(官方文档)[http://doc.oschina.net/grpc?t=58008]

gRPC 一开始由 google 开发,是一款语言中立、平台中立、开源的远程过程调用(RPC)系统。

gRPC 默认使用 protocol buffers,这是 Google 开源的一套成熟的结构数据序列化机制(当然也可以使用其他数据格式如 JSON)。正如你将在下方例子里所看到的,你用 proto files 创建 gRPC 服务,用 protocol buffers 消息类型来定义方法参数和返回类型。本文使用“proto3”版本。
新建一个maven工程:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <grpc.version>1.23.0</grpc.version>
    </properties>
    <artifactId>BlockChainDevelop-gRPC</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>3.9.0</version>
        </dependency>


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

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

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

        <dependency>
            <groupId>io.protostuff</groupId>
            <artifactId>protostuff-core</artifactId>
            <version>1.6.0</version>
        </dependency>

        <dependency>
            <groupId>io.protostuff</groupId>
            <artifactId>protostuff-runtime</artifactId>
            <version>1.6.0</version>
        </dependency>

        <!--        必须引入google guava包 不然报错 java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkArgument(ZLjava/lang/String;CLjava/lang/Object;)V-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>27.1-jre</version>
        </dependency>
    </dependencies>
    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.1</version>
            </extension>
        </extensions>
        <!--        使用protobuf插件生成基本类,mvn install, 然后就在target文件夹下看见生成的类-->
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.5.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.9.0:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.11.0:exe:${os.detected.classifier}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

新建proto文件,注意包结构

放在main下与java同级proto目录下
helloworld.proto
注意java_package的值最好跟你等会要拷贝这些生成类存放的目录一致。

syntax = "proto3";

option java_multiple_files = true;
//生成java代码的package
option java_package = "com.nwnu.blockchain.protobuf";
//创建的javaBean的文件名
option java_outer_classname = "MistralProto";
// 可以生成rpc接口
//option java_generic_services = true;

package com.nwnu.blockchain.protobuf;

//声明一个服务名称
service MistralService {
  //请求参数MistralRequest   响应参数MistralResponse
  rpc SayHello (MistralRequest) returns (MistralResponse);
}

//请求
message MistralRequest {
  string name = 1;
}

//响应
message MistralResponse {
  string message = 1;
}


// protoc --proto_path=src/main/resources/protobuf --java_out=src/main/java src/main/resources/protobuf/hello_world.proto

这个时候就可以根据proto文件生成基本类了,maven install,然后就在target文件夹下看见生成的类:
在target下generated-sources包内
把6个类

MistralProto.java
MistralReques.java
MistralRequestOrBuilder.java
MistralResponse.java
MistralResponseOrBuilder.java
MistralServiceGrpc.java

都拷贝到主目录下。然后新建一个client类,新建一个server类。

package com.nwnu.blockchain.grpc.server;

import com.nwnu.blockchain.protobuf.MistralRequest;
import com.nwnu.blockchain.protobuf.MistralResponse;
import com.nwnu.blockchain.protobuf.MistralServiceGrpc;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

import java.io.IOException;


/**
 * MistralServer
 * <pre>
 *  Version         Date            Author          Description
 * ------------------------------------------------------------
 *  1.0.0           2019/09/11     red        -
 * </pre>
 *
 * @author red
 * @version 1.0.0 2019/9/11 7:55 PM
 * @since 1.0.0
 */
public class MistralServer {
	private int port = 8010;
	private Server server;

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

		System.out.println("------------------- 服务端服务已开启,等待客户端访问 -------------------");

		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {

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

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

	private void blockUntilShutdown() throws InterruptedException {
		if (server != null) {
			server.awaitTermination();
		}
	}

	public static void main(String[] args) throws IOException, InterruptedException {
		final MistralServer server = new MistralServer();
		//启动服务
		server.start();
		//服务一直在线,不关闭
		server.blockUntilShutdown();
	}

	// 定义一个实现服务接口的类
	private class MistralHelloWorldImpl extends MistralServiceGrpc.MistralServiceImplBase {

		@Override
		public void sayHello(MistralRequest mistraRequest, StreamObserver<MistralResponse> responseObserver) {
			// 具体其他丰富的业务实现代码
			System.err.println("server:" + mistraRequest.getName());
			MistralResponse reply = MistralResponse.newBuilder().setMessage(("响应信息: " + mistraRequest.getName())).build();
			responseObserver.onNext(reply);
			responseObserver.onCompleted();
		}
	}
}

package com.nwnu.blockchain.grpc.client;

import com.nwnu.blockchain.protobuf.MistralRequest;
import com.nwnu.blockchain.protobuf.MistralResponse;
import com.nwnu.blockchain.protobuf.MistralServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;

/**
 * MistralClient
 * <pre>
 *  Version         Date            Author          Description
 * ------------------------------------------------------------
 *  1.0.0           2019/09/11     red        -
 * </pre>
 *
 * @author red
 * @version 1.0.0 2019/9/11 5:32 PM
 * @since 1.0.0
 */
public class MistralClient {
	private final ManagedChannel channel;
	private final MistralServiceGrpc.MistralServiceBlockingStub blockingStub;

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

		blockingStub = MistralServiceGrpc.newBlockingStub(channel);
	}

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

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

	}

	public static void main(String[] args) throws InterruptedException {
		MistralClient client = new MistralClient("127.0.0.1", 8010);
		System.out.println("-------------------客户端开始访问请求-------------------");
		for (int i = 0; i < 10; i++) {
			client.greet("hello: " + i);
		}
	}
}



标签:Java,protobuf,gRPC,server,grpc,实例,import,java,com

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有