xml地图|网站地图|网站标签 [设为首页] [加入收藏]

gRPC学习记录,netty源码分析

来源:http://www.ccidsi.com 作者:集成经验 人气:174 发布时间:2019-05-18
摘要:叁.编纂服务端代码 public class HelloWorldServer { private int port = 50051; private Server server; /** * 启动服务 * @throws IOException */ private void start() throws IOException { server = ServerBuilder.forPort(port) .addServic

图片 1图片 2

叁.编纂服务端代码

public class HelloWorldServer {

    private int port = 50051;
    private Server server;

    /**
     * 启动服务
     * @throws IOException
     */
    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.GreeterImplBase {

        public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
            //获取参数
            System.out.println("收到的信息:" req.getName());

            //这里可以放置具体业务处理代码 start

            //这里可以放置具体业务处理代码 end

            //构造返回
            HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: "   req.getName())).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }
}

本节追思一下在服务端运营初始化的时候ServerBootstrap#init(),首要做了有的参数的安插。在那之中对于childGroup,childOptions,childAttrs,childHandler等参数被实行了独立安顿。作为参数和ServerBootstrapAcceptor一道,被用作一个特有的handle,封装到pipeline中。ServerBootstrapAcceptor中的eventLoopworkGroup

 

附录:

连带代码: https://github.com/nl101531/JavaWEB

套接字服务端回看

5.测试

服务端运营后,客户端访问

客户端:

图片 3

Paste_Image.png

服务端:

图片 4

Paste_Image.png

图片 5pipeline结构图

知识点回看

4.编写制定客户端代码

public class HelloWorldClient {

    private final ManagedChannel channel; //一个gRPC信道
    private final GreeterGrpc.GreeterBlockingStub blockingStub;//阻塞/同步 存根

   //初始化信道和存根
    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(true));
    }

    /** Construct client for accessing RouteGuide server using the existing channel. */
    private HelloWorldClient(ManagedChannelBuilder<?> channelBuilder) {
        channel = channelBuilder.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;
        try {
            response = blockingStub.sayHello(request);
        } catch (StatusRuntimeException e) {
            System.out.println("RPC调用失败:" e.getMessage());
            return;
        }
        System.out.println("服务器返回信息:" response.getMessage());
    }

    public static void main(String[] args) throws InterruptedException {
        HelloWorldClient client = new HelloWorldClient("127.0.0.1",50051);
        try {
            for(int i=0;i<5;i  ){
                client.greet("world:" i);
            }
        }finally {
            client.shutdown();
        }
    }
}
  • 为客户端channelpipeline添加childHandler遥想指引的代码,在布署childHandler的时候,使用了ChannelInitializer的3个自定义实例。并且覆盖了其initChannel艺术,改措施获得到pipeline并增添具体的Handler

斩草除根难题是:服务端,互联网IO

gRPC学习记录(贰)--Hello World

标签(空格分隔): javaWEB


在上1篇的欧洲经济共同体领会后,该篇则对应了迅猛上手,入门示例当然依旧是Hello world,该一阶段不必要追究代码,所要求的的目标是先跑通,再回想代码,然后深入分析需求如何文化,再去学什么.


上一节总计了channel代码的架构,通晓了从鼎城channel接口的概念以及一层一层最终分别开客户端channel和劳动端channel。从中也能够体会到虚幻和集成的风味。

from threading import Thread
from socket import *

def talk(conn):
    while True:
        try:
            data = conn.recv(1024)
            if not data: break
            conn.send(data.uuper())
        except ConnectionResetError:
            break
    conn.close()

server = socket()  # 默认TCP
server.bind(('127.0.0.1', 8080))
server.listen(5)

# 链接
while True:
    conn, addr = server.accept()
    print(addr)

    # 通信
    t = Thread(target=talk,args=(conn,))
    t.start()

server.close()


# 复习
from gevent import monkey,spawn;monkey.patch_all()
import time

def f1():
    print('from f1 1')
    time.sleep(3)
    print('from f1 2')

def f2():
    print('from f2 1')
    time.sleep(2)
    print('from f2 2')

def f3():
    print('from f3 1')
    time.sleep(5)
    print('from f3 2')

g1=spawn(f1)
g2=spawn(f2)
g3=spawn(f3)

# 让主线程等任务执行完
g1.join()
g2.join()
g3.join()



from gevent import monkey,spawn;monkey.patch_all()
from socket import *

def talk(conn):
    while True:
        try:
            data = conn.recv(1024)
            if not data: break
            conn.send(data.upper())
        except ConnectionResetError:
            break
    conn.close()

def server(ip,port,backlog=5):
    s = socket()  # 默认TCP
    s.bind((ip, port))
    s.listen(backlog)

    # 链接
    while True:
        conn, addr = s.accept()
        print(addr)

        # 通信
        g = spawn(talk,conn)
        # g.join() # 因为通信里有IO,主线程不需要另外等待的任务

    server.close()

if __name__ == '__main__':
    server('127.0.0.1',8080)

2.编写proto文件

在main目录下树立叁个proto文件夹,然后在中间创建hello.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;
}

接下去实行 mvn compile,就能够转移如下代码,纵然未被标识为源代码目录的话,就右键标记下:

图片 6

Paste_Image.png

 @Override public ChannelFuture register(final ChannelPromise promise) { ObjectUtil.checkNotNull(promise, "promise"); //服务端unsafe是NioMessageUnsafe,客户端的是NioByteUnsafe promise.channel().unsafe().register(this, promise); return promise; }

六.想起深入分析

这1环节很主要,要对那么些HelloWorld的德姆o精晓怎么跑通了.
回顾下在那一个历程中做了何等专门的工作?
1.率先maven引进了四个依附,分别是grpc-netty,grpc-protobuf,grpc-stub.应该是广播发表,种类化,客户端调用三有个别的东西吧.最终在build里面引进了一批东西.
2.写proto文件,大约就是概念了三个劳务接口的输入输出类型,然后使用build里面包车型客车工具,生成一群代码.

//指定proto3格式
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;

//定义了一个service
service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

//定义了一个消息请求体
message HelloRequest {
  string name = 1;
}

//定义了一个消息回复体
message HelloReply {
  string message = 1;
}

3.编克制务端
服务端有如下代码,可以见见这些接口和proto里面定义的接口是千篇一律的.

private class GreeterImpl extends GreeterGrpc.GreeterImplBase{
    public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {};
}

然后使用如下代码把该service绑定,

 server = ServerBuilder.forPort(port)
                              .addService(new GreeterImpl())
                              .build()
                              .start();

四.编写制定客户端代码
客户端通过如下方法创立了三个通讯信道,然后和3个梗阻同步的简报工具blockingStub.

//初始化信道和存根
    public HelloWorldClient(String host,int port){
        this(ManagedChannelBuilder.forAddress(host, port)
                                  .usePlaintext(true));
    }
    private HelloWorldClient(ManagedChannelBuilder<?> channelBuilder) {
        channel = channelBuilder.build();
        blockingStub = GreeterGrpc.newBlockingStub(channel);
    }

然后通过该blockingStub调用服务端方法.

 //客户端方法
    public  void greet(String name){
        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        HelloReply response;
        try {
            response = blockingStub.sayHello(request);
        } catch (StatusRuntimeException e) {
            System.out.println("RPC调用失败:" e.getMessage());
            return;
        }
        System.out.println("服务器返回信息:" response.getMessage());
    }

接下去很当然的就去学proto叁的部分有关文化了.

  • workGroup选用Nio伊夫ntLoop并登记Selector这么些进度在前头学习的《注册Selector》进度同样,分歧的地方是unsafe实例不平等。

本文由68399皇家赌场发布于集成经验,转载请注明出处:gRPC学习记录,netty源码分析

关键词: 68399皇家赌场 极乐科技 rpc 源码 分配

频道精选

最火资讯