Rpc框架:grpc-java客户端与服务端

1.添加maven依赖

    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-netty</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-protobuf</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-stub</artifactId>
      <version>1.6.1</version>
    </dependency>
    <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.3.0:exe:${os.detected.classifier}</protocArtifact>
          <pluginId>grpc-java</pluginId>
          <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.6.1:exe:${os.detected.classifier}</pluginArtifact>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>compile-custom</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>

2.编写proto文件(HelloWorld.proto),并定义一个接口

syntax = "proto3";

option java_package = "com";

package helloworld;

// The greeter 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.编译打包

a:执行mvn package 打包

打包如图所示:

b:将  grpc-my-1.0-SNAPSHOT.jar,添加到maven本地厂库

如:

mvn install:install-file -DgroupId=com.my.grpc -DartifactId=hwb -Dversion=1.0-SNAPSHOT -Dpackaging=jar -Dfile=target/grpc-my-1.0-SNAPSHOT.jar

c:并在项目中添加此jar包:

    <dependency>
      <groupId>com.my.grpc</groupId>
      <artifactId>hwb</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>

4.继承 GreeterGrpc.GreeterImplBase并实现

   创建java类,类名为 HelloServiceGrpc;

import com.GreeterGrpc;
import com.HelloWorld;
import io.grpc.stub.StreamObserver;

public class HelloServiceGrpc extends GreeterGrpc.GreeterImplBase {
    @Override
    public void sayHello(HelloWorld.HelloRequest request, StreamObserver<HelloWorld.HelloReply> responseObserver) {
        String name = request.getName();
        System.out.println("您的名字:" + name);
        HelloWorld.HelloReply.Builder builder = HelloWorld.HelloReply.newBuilder();
        builder.setMessage("小伙子不错的、");
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}

5.server服务端(HelloServer)

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;
public class HelloServer {
    private Server server;
    public static void main(String[] args) throws IOException, InterruptedException {
        final HelloServer server = new HelloServer();
        server.start();
        server.blockUntilShutdown();

    }
    private void start() throws IOException {    /* The port on which the server should run */
        int port = 50051;
        //这个部分启动server
        server = ServerBuilder.forPort(port)
                .addService(new HelloServiceGrpc())
                .build().start();
        System.out.println("Server started, listening on "+ port);
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run(){
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                HelloServer.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();
        }
    }

}

6.client客户端

 

import com.GreeterGrpc;
import com.HelloWorld;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

/**
 * Created by Hua wb on 2018/10/11.
 */
public class HelloClient {
    public static void main(String[] args) {
        ManagedChannel localhost = ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext(true).build();
        GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(localhost);
        HelloWorld.HelloRequest hwb = HelloWorld.HelloRequest.newBuilder().setName("luck").build();
        HelloWorld.HelloReply helloReply = stub.sayHello(hwb);
        System.out.println(helloReply.getMessage());
    }
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值