grpc-java代码实现简单总结

1.新建maven项目,列:grpc-server, grpc-client, grpc-service三大模块

grpc-java代码实现简单总结_第1张图片

2,pom.xml文件



    4.0.0

    com.lsy
    grpc-test
    pom
    1.0-SNAPSHOT
    
        grpc-client
        grpc-server
        grpc-service
    
 
     
         com.google.protobuf
         protobuf-java
         3.1.0
     
     
     
         io.grpc
         grpc-stub
         1.3.0
     
     
         io.grpc
         grpc-protobuf
         1.3.0
     
     
         io.grpc
         grpc-netty
         1.3.0
     
 

    
        
            
                kr.motd.maven
                os-maven-plugin
                1.5.0.Final
            
        
        
            
                org.xolstice.maven.plugins
                protobuf-maven-plugin
                0.5.1
                
                    com.google.protobuf:protoc:1.3.0:exe:${os.detected.classifier}
                    grpc-java
                    io.grpc:protoc-gen-grpc-java:3.1.0:exe:${os.detected.classifier}
                
                
                    
                        
                            compile
                            compile-custom
                        
                    
                
            
        
    

3.编译.proto文件(idea下载插件, 安装protobuf support插件)

syntax="proto3";

option java_multiple_files=true;
option java_package="io.grpc.examples.nameserver";
option java_outer_classname="NameProto";
option objc_class_prefix="NS";

package nameserver;

//定义服务
service NameService{
    // 服务中的方法,用于根据Name类型的参数获得一个Ip类型的返回值
    rpc getIpByName (Name) returns (Ip){}
}

//定义Name消息类型,其中name为其序列为1的字段
message Name{
    string name=1;
}
//定义Ip消息类型,其中ip为其序列为1的字段
message Ip{
    string ip=1;
}

grpc-java代码实现简单总结_第2张图片

4.编译成功后,生成java类文件

grpc-java代码实现简单总结_第3张图片

5,编写服务端代码

package com.lsy;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.examples.nameserver.NameServiceGrpc;


import java.io.IOException;

public class NameServer {

    private static final int DEFAULT_PORT = 50051;

    private int port;//服务端口号

    private Server server;

    public NameServer(int port) {
        this(port,ServerBuilder.forPort(port));
    }

    public NameServer(int port, ServerBuilder serverBuilder){
        this.port = port;
        server = serverBuilder.addService(NameServiceGrpc.bindService(new NameServiceImplBaseImpl())).build();
    }

    private void start() throws IOException {
        server.start();
        System.out.println("Server has started, listening on " + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                NameServer.this.stop();
            }
        });
    }
    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 {

        NameServer nameServer;

        if(args.length > 0){
            nameServer = new NameServer(Integer.parseInt(args[0]));
        }else{
            nameServer = new NameServer(DEFAULT_PORT);
        }
        nameServer.start();
        nameServer.blockUntilShutdown();
    }
}


    
        grpc-test
        com.lsy
        1.0-SNAPSHOT
    
    4.0.0

    grpc-server
    grpc-server

       
           
               com.lsy
               grpc-service
               1.0-SNAPSHOT
           
       
    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.6
                    1.6
                
            
        
    

6.编写客户端代码

package com.lsy;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.examples.nameserver.Ip;
import io.grpc.examples.nameserver.Name;
import io.grpc.examples.nameserver.NameServiceGrpc;


import java.util.concurrent.TimeUnit;

/**
 * Created by lsy on 2019/2/14.
 */
public class NameClient {

    private static final String DEFAULT_HOST = "localhost";

    private static final int DEFAULT_PORT = 50051;

    private ManagedChannel managedChannel;

    private NameServiceGrpc.NameServiceBlockingStub nameServiceBlockingStub;

    public NameClient(String host, int port) {
        this(ManagedChannelBuilder.forAddress(host,port).usePlaintext(true).build());
    }

    public NameClient(ManagedChannel managedChannel) {
        this.managedChannel = managedChannel;
        this.nameServiceBlockingStub = NameServiceGrpc.newBlockingStub(managedChannel);
    }

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

    public String getIpByName(String n){
        Name name = Name.newBuilder().setName(n).build();
        Ip ip = nameServiceBlockingStub.getIpByName(name);
        return ip.getIp();
    }

    public static void main(String[] args) {
        NameClient nameClient = new NameClient(DEFAULT_HOST,DEFAULT_PORT);
            String res = nameClient.getIpByName("Sunny");
            System.out.println("ip是:" + res );
    }
}



    
        grpc-test
        com.lsy
        1.0-SNAPSHOT
    
    4.0.0

    grpc-client
    grpc-client

      
          
              com.lsy
              grpc-service
              1.0-SNAPSHOT
          
      
    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.6
                    1.6
                
            
        
    

7.grpc-service pom.xml



    
        grpc-test
        com.lsy
        1.0-SNAPSHOT
    
    4.0.0

    grpc-service
    grpc-service

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.6
                    1.6
                
            
        
    

8.实现提供的服务(NameServiceImplBaseImpl类)

package com.lsy;

import io.grpc.examples.nameserver.Ip;
import io.grpc.examples.nameserver.Name;
import io.grpc.examples.nameserver.NameServiceGrpc;
import io.grpc.stub.StreamObserver;

import java.util.HashMap;
import java.util.Map;


public class NameServiceImplBaseImpl implements NameServiceGrpc.NameService {

    private Map map = new HashMap();

    public NameServiceImplBaseImpl() {
        map.put("Sunny","125.216.242.51");
        map.put("David","117.226.178.139");
    }
    public String getName(String name){
        String ip = map.get(name);
        if(ip == null){
            return "0.0.0.0";
        }
        return ip;
    }

    @Override
    public void getIpByName(Name request, StreamObserver responseObserver) {
        Ip ip = Ip.newBuilder().setIp(getName(request.getName())).build();
        responseObserver.onNext(ip);
        responseObserver.onCompleted();
    }
}

你可能感兴趣的:(grpc-java代码实现简单总结)