grpc HelloWorld

一.创建 maven 项目

版本信息

<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <grpc.version>1.34.1</grpc.version><!-- CURRENT_GRPC_VERSION -->
    <protobuf.version>3.12.0</protobuf.version>
    <protoc.version>3.12.0</protoc.version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>a.b.c</groupId>
    <artifactId>grpc-java-learning</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <grpc.version>1.34.1</grpc.version><!-- CURRENT_GRPC_VERSION -->
        <protobuf.version>3.12.0</protobuf.version>
        <protoc.version>3.12.0</protoc.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.grpc</groupId>
                <artifactId>grpc-bom</artifactId>
                <version>${grpc.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java-util</artifactId>
            <version>${protobuf.version}</version>
        </dependency>
    </dependencies>
    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.2</version>
            </extension>
        </extensions>
        <plugins>
            <!-- 编译 proto 的 maven 插件 -->
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
                   <!-- proto 协议文件所在的目录 -->
                    <protoSourceRoot>src/main/proto</protoSourceRoot>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
						<!-- maven 编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

二.HelloWorld 快速上手

1.编写 protocol buffers 定义接口

创建.proto 文件 src/main/proto/helloworld.proto,定义服务输入和输出的数据结构

syntax = "proto3";

option java_multiple_files = true;
// 编译生成的 java 包名
option java_package = "com.grpc.examples.helloworld";
// 编译生成的 java 类名
option java_outer_classname = "HelloWorldProto";



// 定义一个服务
service HelloWordServer {
  // 定义两个服务的输入和输出数据结构
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}

// 请求的数据结构
message HelloRequest {
  string name = 3;
}

// 相应的数据结构
message HelloReply {
  string message = 1;
}

2.maven 编译项目

target/generated-sources/protobuf/grpc-java/com/grpc/examples/helloworld/HelloWordServerGrpc.java目录下生成com.grpc.examples.helloworld.HelloWordServerGrpc

3.编写服务端代码

要求实现继承 HelloWordServerGrpc.HelloWordServerImplBase ,重写 sayHello 方法

package grpc.examples.helloworld;

import com.grpc.examples.helloworld.HelloReply;
import com.grpc.examples.helloworld.HelloRequest;
import com.grpc.examples.helloworld.HelloWordServerGrpc;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

/**
 * 服务端
 */
public class HelloWordServer extends HelloWordServerGrpc.HelloWordServerImplBase {

    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {

        String name = request.getName();
        String message = syaHello(name);

        responseObserver.onNext(HelloReply.newBuilder().setMessage(message).build());
        responseObserver.onCompleted();

    }

    private String syaHello(String name) {
        return "hello " + name + ", I am HelloWordServer.";
    }

    public static void main(String[] args) throws Exception {
        ServerBuilder.forPort(9999)
                .addService(new HelloWordServer())
                .build()
                .start();
        System.out.println("server start at 9999");

        Thread.sleep(9999999);
    }
}

4.编写客户端代码

要求 ip 和 port 和服务端一致

package grpc.examples.helloworld;


import com.grpc.examples.helloworld.HelloReply;
import com.grpc.examples.helloworld.HelloRequest;
import com.grpc.examples.helloworld.HelloWordServerGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class HelloWorldClient {
  HelloWordServerGrpc.HelloWordServerBlockingStub stub;
  ManagedChannel channel;

  public static void main(String[] args) {

    HelloWorldClient client = new HelloWorldClient();

    HelloReply reply = client.stub.sayHello(HelloRequest.newBuilder().setName("张三").build());

    System.out.println(reply.getMessage());
  }

  public HelloWorldClient(){
    channel = ManagedChannelBuilder
        .forAddress("127.0.0.1",9999)
        .usePlaintext()
        .build();
    stub =
        HelloWordServerGrpc.newBlockingStub(channel);
  }
}

5.测试

启动服务端代码,输出server start at 9999

启动客户端代码,输出hello 张三, I am HelloWordServer.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值