[pravega-017] pravega源码分析--Controller子项目--ControllerServiceStarter启动的服务--gRpc服务

1.先从grpc开始。

2.grpc的官网

https://grpc.io

grpc的github

https://github.com/grpc/grpc

grpc-java

https://github.com/grpc/grpc-java

3.实现一个最简单的java grcp

3.1参考文档 https://github.com/grpc/grpc-java

3.2 idea安装protobuf插件。file-->settings-->plugins-->browse repositories-->搜索 protobuf Support插件-->install

3.3 根据grpc-java的官方example改写。在idea新建两个gradle项目HiGRPCServer和HiGRPCClient。两个项目分别打包成独立可运行jar包。先在一个终端启动HiRPCServer开启服务,再在另一个终端启动HiRPCClient进行RPC调用。

3.4.HiGRPC源码

3.4.1 项目文件目录如下:

 ├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   ├── java
    │   │   └── HelloWorldServer.java
    │   ├── proto
    │   │   └── helloworld.proto
    │   └── resources
    └── test
        ├── java
        └── resources
 

3.4.2 build.gradle文件

group 'com.brian.demo.grpc'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'com.google.protobuf'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    main {
        java {
            srcDir 'build/generated/source/proto/main/java'
            srcDir 'build/generated/source/proto/main/grpc'
        }
    }
}

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.5'
    }
}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.5.1-1"
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.18.0'
        }
    }
    generateProtoTasks {
        all()*.plugins {
            grpc {}
        }
    }
}

dependencies {
    compile 'io.grpc:grpc-netty-shaded:1.18.0'
    compile 'io.grpc:grpc-protobuf:1.18.0'
    compile 'io.grpc:grpc-stub:1.18.0'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

//打一个jar包
jar {
    from {
        //添加依赖到打包文件
        //configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
        configurations.runtime.collect{zipTree(it)}
    }
    manifest {
        attributes 'Main-Class': 'HelloWorldClient'
    }
}
注意:如果jar部分写成如下方式,是打多个jar包
//jar {
//    String someString = ''
//    configurations.runtime.each {someString = someString + " lib/"+it.name} //遍历项目的所有依赖的jar包赋值给变量someString
//    manifest {
//        attributes 'Main-Class': 'HelloWorldServer'
//        attributes 'Class-Path': someString
//    }
//}

//清理整个项目
task clearPj(type:Delete){
    delete 'build','target'
}

//把运行期的jar胞复制到build/libs/lib目录
task copyJar(type:Copy){
    from configurations.runtime
    into ('build/libs/lib')
}

//release版本,最终结果。
task release(type: Copy,dependsOn: [build,copyJar]) {
    //    from  'conf'
    //   into ('build/libs/eachend/conf')
}

3.4.3 helloworld.proto文件

syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

3.4.4 HelloWorldServer.java


import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.logging.Logger;

import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.*;

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

    private Server server;

    private void start() throws IOException {
    /* The port on which the server should run */
        int port = 50051;
        server = ServerBuilder.forPort(port)
                .addService(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();
    }

    static class GreeterImpl extends GreeterGrpc.GreeterImplBase {

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

3.4.5 编译:./gradlew release 。此时,在builde/libs生成jar包 HiGRPCServer-1.0-SNAPSHOT.jar 。

3.4.6 启动服务: java -jar HiGRPCServer-1.0-SNAPSHOT.jar

3.5 HiGRPCClient项目

3.5.1 项目文件目录结构

.
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   ├── java
    │   │   └── HelloWorldClient.java
    │   ├── proto
    │   │   └── helloworld.proto
    │   └── resources
    └── test
        ├── java
        └── resources
3.5.2 hellowrold.proto,这个文件跟3.4.3是一样的。不列出了。

3.5.3 HelloWorldClient.java文件


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;

import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.*;


/**
 * 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) {
        this(ManagedChannelBuilder.forAddress(host, port)
                // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
                // needing certificates.
                .usePlaintext()
                .build());
    }

    /** Construct client for accessing HelloWorld server using the existing channel. */
    HelloWorldClient(ManagedChannel channel) {
        this.channel = channel;
        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).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 {
      /* Access a service running on the local machine on port 50051 */
            String user = "world";
            if (args.length > 0) {
                user = args[0]; /* Use the arg as the name to greet if provided */
            }
            client.greet(user);
        } finally {
            client.shutdown();
        }
    }
}

3.5.4 编译 ./gradlew release。完成后,在build/libs目录下生成 HiGRPCClient-1.0-SNAPSHOT.jar

3.5.5 执行 java -jar HiGRPCClient-1.0-SNAPSHOT.jar,输出结果"Greeting: Hello world"

4.grpc的技术细节暂时不写了,根据示例对照文档查阅即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值