grpc--demo(参考官网说明看demo)

这篇博客介绍了如何使用gRPC进行服务端和客户端的开发。首先,讲述了在gradle配置文件中如何引入gRPC依赖。接着,详细解析了.proto文件的作用。然后,展示了服务端代码的实现,包括自定义服务端接口实现类和启动类的编写。最后,讲解了客户端如何调用服务端接口的代码实现。

1.gradle配置文件(官网上有gradle及maven的配置说明)

plugins {
    id 'java'
    id 'com.google.protobuf' version '0.8.8'
}

group 'com.hgl.dp.io.grpc'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {

    maven{
        url "http://maven.aliyun.com/nexus/content/groups/public/"
    }
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile 'io.grpc:grpc-netty-shaded:1.20.0'
    compile 'io.grpc:grpc-protobuf:1.20.0'
    compile 'io.grpc:grpc-stub:1.20.0'

}


tasks.withType(JavaCompile) {
    options.encoding = "UTF-8"
}

protobuf {
//配置生成的java类的根目录
    generatedFilesBaseDir = "$projectDir/src/"
    protoc {
        artifact = "com.google.protobuf:protoc:3.7.1"
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.20.0'
        }
    }
    generateProtoTasks {
        all()*.plugins {
            grpc {

                outputSubDir = 'java'
            }
        }
    }
}

2.proto文件

syntax = "proto3";

option java_multiple_files = true;
option java_package = "com.hgldp.grpc";
option java_outer_classname = "SimPleProto";


service ExampleGrpc{
    rpc sendSimpleMessage(HelloRequest) returns(HelloResponse){}
    rpc getListMessage(HelloRequest) returns(stream StudentResponse){}

    rpc getStudentList(stream HelloRequest) returns(StudentResponseList){}

    rpc BiTalk(stream StreamRequest) returns(stream StreamResponse){}
}


message HelloRequest{

    string no = 1;
}

message HelloResponse{
    string name=1;
}


message StudentResponse{

    string name = 1;
    int32 age = 2;
    string city = 3;
}

message StudentResponseList{
    repeated StudentResponse studentResponse = 1;
}


message StreamRequest{
    string request_info = 1;
}

message StreamResponse{
    string response_info = 1;
}

3.服务端代码(服务端接口实现类和服务端启动类可以分开,也可以放在一起,看自己喜好)
3.1 自定义服务端实现类

package com.hgldp.server;

import com.hgldp.grpc.*;
import io.grpc.stub.StreamObserver;

import java.util.UUID;

public class GrpcServerImpl extends ExampleGrpcGrpc.ExampleGrpcImplBase{


    /**
       简单模型
     */
    @Override
    public void sendSimpleMessage(HelloRequest request, StreamObserver<HelloResponse&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值