【JAVA】gRPC使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://xxlcube.blog.csdn.net/article/details/76686209

安装proto 3.+版本

参照http://blog.csdn.net/simonchi/article/details/76495696


写好proto文件

peroson.proto  对象定义文件

syntax="proto3";
package com.cmcc.protobuf;
option java_outer_classname="PersonProbuf";

message Person {
	string username=1;
	int32 age=2;
	string sex=3;
}

message Req {
	string username=1;
}

message Resp {
	Person person=1;
}
service.proto 服务定义文件

syntax="proto3";
package com.cmcc.protobuf;
import "person.proto";

service UserService {
	rpc query(Req) returns (Resp) {}
}
具体proto文件的语法参照官方https://developers.google.com/protocol-buffers/docs/proto3

然后通过proto生成person和service的代码

protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto

然后执行mvn clean install最后会在target目录下生成服务的rpc的代码,拷贝到src目录下即可


编写服务端代码

package com.cmcc.grpc;

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

import com.cmcc.protobuf.PersonProbuf;
import com.cmcc.protobuf.PersonProbuf.Req;
import com.cmcc.protobuf.PersonProbuf.Resp;
import com.cmcc.protobuf.UserServiceGrpc;

/**
 * @Type GrpcServer.java
 * @Desc 
 * @author chiwei
 * @date 2017年8月2日 下午2:51:12
 * @version 
 */
/**
 * @author chiwei
 *
 */
public class GrpcServer {

    private int port = 50011;
    private Server server;

    private void start() throws Exception {
        server = ServerBuilder.forPort(port).addService(new UserServiceImpl()).build().start();
        System.out.println("user service start ...");
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                super.run();
                System.out.println("shutting down gRPC server since JVM is shutting down");
                GrpcServer.this.stop();
                System.out.println("server shut down");
            }

        });
    }

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

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

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        GrpcServer server = new GrpcServer();
        server.start();
        server.blockUntilShutdown();
    }

    private class UserServiceImpl extends UserServiceGrpc.UserServiceImplBase {

        @Override
        public void query(Req request, StreamObserver<Resp> responseObserver) {
            // TODO Auto-generated method stub
            System.out.println("service:" + request.getUsername());
            PersonProbuf.Person rp = PersonProbuf.Person.newBuilder()
                    .setUsername(request.getUsername()).setAge(100).build();
            Resp resp = Resp.newBuilder().setPerson(rp).build();
            responseObserver.onNext(resp);
            responseObserver.onCompleted();
        }

    }

}

/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年8月2日 chiwei create
 */

编写客户端代码

package com.cmcc.grpc;

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

import java.util.concurrent.TimeUnit;

import com.cmcc.protobuf.PersonProbuf.Req;
import com.cmcc.protobuf.PersonProbuf.Resp;
import com.cmcc.protobuf.UserServiceGrpc;

/**
 * @Type GrpcClient.java
 * @Desc 
 * @author chiwei
 * @date 2017年8月2日 下午3:20:09
 * @version 
 */
/**
 * @author chiwei
 *
 */
public class GrpcClient {

    private ManagedChannel channel;
    private UserServiceGrpc.UserServiceBlockingStub blockingStub;

    public GrpcClient(String host, int port) {
        channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
        blockingStub = UserServiceGrpc.newBlockingStub(channel);
    }

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

    public void query(String name) {
        Req req = Req.newBuilder().setUsername(name).build();
        Resp resp = blockingStub.query(req);
        System.out.println("客户端获取服务端响应信息:" + resp.getPerson());
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        GrpcClient client = new GrpcClient("127.0.0.1", 50011);
        for (int i = 0; i < 5; i++) {
            client.query("chiwei" + i);
        }

    }

}

/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年8月2日 chiwei create
 */

执行即可。

pom文件如下:

<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>

	<groupId>grpc</groupId>
	<artifactId>grpc</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>grpc</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<grpc.version>1.0.1</grpc.version>
	</properties>
	<dependencies>
		<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>com.google.protobuf</groupId>
			<artifactId>protobuf-java</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>io.grpc</groupId>
			<artifactId>grpc-core</artifactId>
			<version>${grpc.version}</version>
		</dependency>
		<dependency>
			<groupId>io.grpc</groupId>
			<artifactId>grpc-all</artifactId>
			<version>${grpc.version}</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>com.ytf.rpc.demo</finalName>
		<extensions>
			<extension>
				<groupId>kr.motd.maven</groupId>
				<artifactId>os-maven-plugin</artifactId>
				<version>1.5.0.Final</version>
			</extension>
		</extensions>
		<plugins>
			<plugin>
				<groupId>org.xolstice.maven.plugins</groupId>
				<artifactId>protobuf-maven-plugin</artifactId>
				<version>0.5.0</version>
				<configuration>
					<protocArtifact>com.google.protobuf:protoc:3.1.0:exe:${os.detected.classifier}</protocArtifact>
					<pluginId>grpc-java</pluginId>
					<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.0.1: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>
				<version>2.3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>





这是官网的一张图,支持多语言




展开阅读全文

没有更多推荐了,返回首页