1. 程式人生 > >grpc學習筆記--Java版

grpc學習筆記--Java版

這幾天由於工作的原因,涉及到系統之間的通訊,rpc呼叫方式不失為內部系統之間的一種高效簡單的方式,至於rpc是什麼,這裡不多說,自行Google去。
在比較了Thrift(Apache開源專案)和grpc(谷歌去年開源的一個專案)後,選擇了grpc,這裡不想多說它們兩個之間的區別。
在閱讀下面程式碼之前你先要去了解一下protocol buffer
本文涉及的程式,用的開發工具是idea2016.2.5,java環境是jdk1.8。
用idea新建一個maven專案,Id資訊如下

<groupId>com.mingluck.test</groupId>
<artifactId
>
grpc</artifactId>

建立如下的目錄結構(包括檔案)
grpc
看下面的test.proto的內容:

syntax = "proto3";
package grpc;
option java_package = "com.mingluck.grpc";
option java_outer_classname = "HelloWorldServiceProto";
option java_multiple_files = true;

//服務端介面類
service Greeter {
  //服務端介面方法
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

//請求引數
message
HelloRequest { string name = 1; string sex = 2; } //響應引數 message HelloReply { string message = 1; }

其中java_package 指定了生成的類的包名
pom.xml如下

<?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> <groupId>com.mingluck.test</groupId> <artifactId>grpc</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-all</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.4.2</version> </dependency> </dependencies> <build> <extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.4.1.Final</version> </extension> </extensions> <plugins> <!-- protobuf --> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.5.0</version> <configuration> <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> <protoSourceRoot>src/main/resources/proto</protoSourceRoot> </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>

然後在cmd視窗中切換到專案pom.xml檔案所在的目錄,執行mvn compile命令,執行命令後目錄結構會變成如下
grpc
接下來可以寫程式碼了,先實現服務端程式,HelloWorldServer.java

package com.mingluck.grpc;
/**
 * Created by Darren on 2016/11/11.
 */
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

public class HelloWorldServer {
    private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());

    /* The port on which the server should run */
    private int port = 50051;
    private Server server;

    private void start() throws IOException {
        server = ServerBuilder.forPort(port)
                .addService(GreeterGrpc.bindService(new GreeterImpl()))
                .build()
                .start();
        logger.info("Server started, listening on " + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                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();
        }
    }

    /**
     * Await termination on the main thread since the grpc library uses daemon threads.
     */
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    /**
     * Main launches the server from the command line.
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        final HelloWorldServer server = new HelloWorldServer();
        server.start();
        server.blockUntilShutdown();
    }

    private class GreeterImpl implements GreeterGrpc.Greeter {
        /** 原子Integer */
        public AtomicInteger count = new AtomicInteger(0);

        @Override
        public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
            System.out.println("call sayHello");
            HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName() + req.getSex()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
            System.out.println(count.incrementAndGet() + Thread.currentThread().getName());
        }
    }
}

注意sayHello方法的重寫
接下來實現HelloWorldClient.java

package com.mingluck.grpc;

/**
 * Created by Darren on 2016/11/11.
 */
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 * A simple client that requests a greeting from the {@link HelloWorldServer}.
 */
public class HelloWorldClient {
    private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());

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

    /** Construct client connecting to HelloWorld server at {@code host:port}. */
    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);
    }

    /** Say hello to server. */
    public void greet(String name) {
        logger.info("Will try to greet " + name + " ...");
        HelloRequest request = HelloRequest.newBuilder().setName(name).setSex(" 女").build();
        HelloReply response;
        try {
            response = blockingStub.sayHello(request);
        } catch (StatusRuntimeException e) {
            logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
            return;
        }
        logger.info("Greeting: " + response.getMessage());
    }

    /**
     * Greet server. If provided, the first element of {@code args} is the name to use in the
     * greeting.
     */
    public static void main(String[] args) throws Exception {
        HelloWorldClient client = new HelloWorldClient("localhost", 50051);
        try {

            String user = "world";
            if (args.length > 0) {
                user = args[0];
            }
            client.greet(user);
        } finally {
           client.shutdown();
        }
    }
}

分別執行服務端和客戶端,會看到rpc呼叫成功。
為了防止客戶端不斷呼叫帶來的開銷(短連線),下面的例子給出了連線池的方式,程式碼如下

package com.mingluck.grpc;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/**
 * Created by darren on 2016/11/14.
 */
public class HelloWorldClientFactory extends BasePooledObjectFactory<HelloWorldClient> {

    @Override
    public HelloWorldClient create() throws Exception {
        return new HelloWorldClient("localhost", 50051);
    }

    @Override
    public PooledObject<HelloWorldClient> wrap(HelloWorldClient client) {
        return new DefaultPooledObject<HelloWorldClient>(client);
    }

    @Override
    public void destroyObject(PooledObject<HelloWorldClient> p) throws Exception {
        HelloWorldClient client = p.getObject();
        client.shutdown();
        super.destroyObject(p);
    }

    public static void main(String[] args) throws Exception {

        /** 連線池的配置 */
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

        /** 下面的配置均為預設配置,預設配置的引數可以在BaseObjectPoolConfig中找到 */
        poolConfig.setMaxTotal(8); // 池中的最大連線數
        poolConfig.setMinIdle(0); // 最少的空閒連線數
        poolConfig.setMaxIdle(8); // 最多的空閒連線數
        poolConfig.setMaxWaitMillis(-1); // 當連線池資源耗盡時,呼叫者最大阻塞的時間,超時時丟擲異常 單位:毫秒數
        poolConfig.setLifo(true); // 連線池存放池化物件方式,true放在空閒佇列最前面,false放在空閒佇列最後
        poolConfig.setMinEvictableIdleTimeMillis(1000L * 60L * 30L); // 連線空閒的最小時間,達到此值後空閒連線可能會被移除,預設即為30分鐘
        poolConfig.setBlockWhenExhausted(true); // 連線耗盡時是否阻塞,預設為true

        /** 連線池建立 */
        GenericObjectPool<HelloWorldClient> objectPool = new GenericObjectPool<HelloWorldClient>(new HelloWorldClientFactory(), poolConfig);


        new Thread(makeTask(objectPool)).start();
        new Thread(makeTask(objectPool)).start();
        new Thread(makeTask(objectPool)).start();
        new Thread(makeTask(objectPool)).start();

        Thread.sleep(100000);

    }

    private static Runnable makeTask(GenericObjectPool<HelloWorldClient> objectPool){
        return () -> {
            HelloWorldClient client = null;
            try {
                client = objectPool.borrowObject();

            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                String req = "world!";
                client.greet(req);
            } finally {
                /** 將連線物件返回給連線池 */
               objectPool.returnObject(client);
            }
        };
    }
}

上面程式碼測試通過,程式碼比較簡單,應該看得懂。