[web-023]RPC和gRPC(02)

1.gRPC的官网文档

https://grpc.io/docs/

2.本例修改自https://github.com/jpdna/gRPC-maven-helloworld

3.项目目录结构

├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── org
    │   │       └── grpchello
    │   │           ├── HelloClient.java
    │   │           └── HelloServer.java
    │   └── proto
    │       └── hello.proto
    └── test
        └── java
            └── org
                ├── grpchello
                │   └── AppTest.java

4.pom.xml

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.grpchello</groupId>
  <artifactId>grpctest</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>grpctest</name>
  <url>http://maven.apache.org</url>

  <properties>
    <compileSource>1.8</compileSource>
  </properties>


  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-all</artifactId>
      <version>0.9.0</version>
    </dependency>
  </dependencies>


  <pluginRepositories>
    <pluginRepository>
      <releases>
	      <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
	      <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </pluginRepository>
    <pluginRepository>
      <id>protoc-plugin</id>
      <url>https://dl.bintray.com/sergei-ivanov/maven/</url>
    </pluginRepository>
  </pluginRepositories>

  <build>
    <extensions>
      <extension>
	      <groupId>kr.motd.maven</groupId>
	      <artifactId>os-maven-plugin</artifactId>
	      <version>1.4.0.Final</version>
      </extension>
    </extensions>
    <plugins>
      <plugin>
	      <groupId>com.google.protobuf.tools</groupId>
	      <artifactId>maven-protoc-plugin</artifactId>
	      <version>0.4.2</version>
	      <configuration>
	        <protocArtifact>com.google.protobuf:protoc:3.0.0-beta-1:exe:${os.detected.classifier}</protocArtifact>
	        <pluginId>grpc-java</pluginId>
	        <pluginArtifact>io.grpc:protoc-gen-grpc-java:0.9.0:exe:${os.detected.classifier}</pluginArtifact>
	      </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>
	      <version>3.2</version>
	      <configuration>
	        <source>${compileSource}</source>
	        <target>${compileSource}</target>
	        <showDeprecation>true</showDeprecation>
	        <showWarnings>true</showWarnings>
	        <encoding>UTF-8</encoding>
	      </configuration>
      </plugin>

      
      <plugin>
	      <groupId>org.apache.maven.plugins</groupId>
	      <artifactId>maven-assembly-plugin</artifactId>
	      <version>2.4</version>
	      <configuration>
	        <archive>
	          <manifest>
	            <mainClass>jpmygroup.App</mainClass>
	          </manifest>
	        </archive>
	        <descriptorRefs>
	          <descriptorRef>jar-with-dependencies</descriptorRef>
	          </descriptorRefs>
	        </configuration>
        <executions>
	        <execution>
	          <id>make-jar-with-dependencies</id>
	          <phase>package</phase>
	          <goals>
	            <goal>single</goal>
	          </goals>
	        </execution>
	      </executions>
      </plugin>

    </plugins>
  </build>
  

</project>

5.hello.proto

syntax = "proto3";

package helloworld;

option java_multiple_files = true;
option java_package = "org.grpchello";
option java_outer_classname = "HelloProto";

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string message = 1;
}

6.HelloServer.java

package org.grpchello;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;


public class HelloServer {
  private int port = 50051;
  private Server server;

  private void start() throws Exception {
    server = ServerBuilder.forPort(port)
            .addService(GreeterGrpc.bindService(new GreeterGrpc.Greeter() {
              @Override
              public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
                HelloResponse reply = HelloResponse.newBuilder().setMessage("Hello " + request.getName()).build();
                responseObserver.onNext(reply);
                responseObserver.onCompleted();
              }
            }))
            .build()
            .start();
  }

  public static void main(String[] args) throws Exception {
    final HelloServer helloServer = new HelloServer();
    helloServer.start();
    helloServer.server.awaitTermination();
  }

}

7.HelloClient.java

package org.grpchello;

import java.util.concurrent.TimeUnit;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;


public class HelloClient {

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

  public HelloClient(String host, int port) {
    channel = ManagedChannelBuilder.forAddress(host, port)
        .usePlaintext(true)
        .build();
    greeterBlockingStub = GreeterGrpc.newBlockingStub(channel);
  }

  public void shutdown() throws InterruptedException {
    channel.shutdown().awaitTermination(2, TimeUnit.SECONDS);
  }

  public String greet(String name) {
    try {
      HelloRequest request = HelloRequest.newBuilder().setName(name).build();
      HelloResponse response = greeterBlockingStub.sayHello(request);
      return response.getMessage();
    } catch (RuntimeException e) {
      return "?";
    }
  }

  public static void main(String[] args) throws Exception {
    HelloClient client = new HelloClient("localhost", 50051);
    try {
      String user = "world";
      System.out.println(client.greet(user));
    } finally {
      client.shutdown();
    }
  }
}

8.编译

mvn clean package

9.运行服务端

java -cp target/grpctest-1.0-SNAPSHOT-jar-with-dependencies.jar org.grpchello.HelloServer

10.运行客户端

java -cp target/grpctest-1.0-SNAPSHOT-jar-with-dependencies.jar org.grpchello.HelloClient

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值