gRPC编译和安装——Linux版

一、安装

1、安装依赖环境

sudo apt-get install pkg-config
sudo apt-get install autoconf automake libtool make g++ unzip
sudo apt-get install libgflags-dev libgtest-dev
sudo apt-get install clang libc++-dev

2、下载源码

国内镜像(githup上下载超慢,尤其是后面的submodule)

git clone https://gitee.com/mirrors/grpc-framework grpc

3、修改submodule

cd grpc
cat .gitmodules // 查看文件里的submodule, 将GitHub改成Gitee

4、更新submodule

cd grpc
git submodule update --init 

5、安装gRPC

cd grpc
mkdir build
cd build
// 指定安装路径 /usr/local 
cmake -DCMAKE_INSTALL_PREFIX=/usr/local ..
make -j2
sudo make install

二、测试

代码结构,这里客户端分为C++版和Python两个版本

├── client.py
└── ubuntu
    ├── client_cpp
    │   ├── CMakeLists.txt
    │   └── main.cpp
    ├── protos
    │   ├── helloworld.grpc.pb.cc
    │   ├── helloworld.grpc.pb.h
    │   ├── helloworld.pb.cc
    │   ├── helloworld.pb.h
    │   ├── helloworld.proto
    │   ├── helloworld_pb2.py
    │   └── helloworld_pb2_grpc.py
    └── server_cpp
        ├── CMakeLists.txt
        └── main.cpp

1、proto文件

helloworld.proto

syntax = "proto3";

option java_package = "ex.grpc";

package helloworld;

message Reply {
    int32 result = 1;
}

message HelloMessage {
    int32 a = 1;
    int32 b = 2;
}

service TestServer {
    rpc hello_request (HelloMessage) returns (Reply) {}
}

生成c++和python对应的文件

(1)C++:

cd protos
protoc --cpp_out=. helloworld.proto
protoc --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` helloworld.proto

这里会报错:pro-gen-grpc插件没找到,全局搜索了下这个插件 是在目录下/home/package/build_grpc/grpc/build/grpc_cpp_plugin

为什么在编译源码时,没将build下的动态库放到系统环境/usr/local/bin下

两种解决方法:

1.可自己将上面插件路径设置到环境变量

2.将该插件拷贝到/usr/local/bin目录下

 生成的目录:

(2)Python:

cd protos
python3 -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. helloworld.proto

2、gRPC服务端(C++)

main.cpp

#include <string>
#include <grpcpp/grpcpp.h>
#include "protos/helloworld.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;

using helloworld::TestServer;
using helloworld::HelloMessage;
using helloworld::Reply;

class HelloServiceImplementation final : public TestServer::Service {
    Status hello_request(
            ServerContext* context,
            const HelloMessage* request,
            Reply* reply
    ) override {
        int a = request->a();
        int b = request->b();
        reply->set_result(a * b);
        return Status::OK;
    }
};

void Run() {
    std::string address("0.0.0.0:5000");
    HelloServiceImplementation service;
    ServerBuilder builder;
    builder.AddListeningPort(address, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);
    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "Server listening on port: " << address << std::endl;
    server->Wait();
}

int main(int argc, char** argv) {
    Run();
    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.17)

project(grpcdemo)

set(CMAKE_CXX_STANDARD 14)

find_package(Protobuf REQUIRED)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GRPCPP REQUIRED grpc++>=1.22.0)

include_directories(
        ${GRPCPP_INCLUDE_DIRS} # /usr/local/Cellar/grpc/1.29.1/include
        ${Protobuf_INCLUDE_DIRS} # /usr/local/include
)

link_directories(
        ${GRPCPP_LIBRARY_DIRS}
)


add_library(hellolibrary ../protos/helloworld.grpc.pb.cc ../protos/helloworld.pb.cc )

target_link_libraries(hellolibrary
        protobuf::libprotobuf # 将protobuf加到hellolibrary, 因为在hellolibrary 使用了protobuf
    )

add_executable(server_bin main.cpp)

target_link_libraries(server_bin
        ${GRPCPP_LIBRARIES}
        hellolibrary
        )

3、gRPC客户端(Python/C++)

client.py

import grpc
from protos import helloworld_pb2
from protos import helloworld_pb2_grpc
from google.protobuf.json_format import ParseDict
import time


class HelloBusiness(object):

    def __init__(self):
        super(HelloBusiness, self).__init__()
        self.ip = "127.0.0.1"
        self.port = 5000
        self.client_init()

    def client_init(self):
        """
        gRPC客户端初始化
        :return: None
        """

        self.channel = grpc.insecure_channel('{}:{}'.format(self.ip, self.port))
        self.client = helloworld_pb2_grpc.TestServerStub(self.channel)

        return None

    def hello_business(self, msg):
        """

        :param msg: request msg
        :return:
        """

        proto_data = helloworld_pb2.HelloMessage()  #
        ParseDict(msg, proto_data)  # 格式化msg
        response = self.client.hello_request.future(proto_data)  # 向server发送数据
        response.add_done_callback(self.hello_callback)  # 回调函数, 发送数据使用异步[future]时, 必须加回调函数

        return response

    def hello_callback(self, future):

        print(future.result().result)
        print("callback")

class HelloWorld(HelloBusiness):

    def hello(self, *args, **kwargs):
        """

        :return: None
        """

        self.hello_business({
            "a": 1,
            "b": 2,
        })

        return None


grpc_client = HelloWorld()

if __name__ == '__main__':

    grpc_client.hello()
    time.sleep(2)

C++

#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/grpcpp.h>

#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "../protos/helloworld.grpc.pb.h"
#endif

using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::TestServer;
using helloworld::HelloMessage;
using helloworld::Reply;


class GreeterClient {
public:

    GreeterClient(std::shared_ptr<Channel> channel):stub_(TestServer::NewStub(channel)) {}

    int say_hello(const std::string& user) {

        HelloMessage request;
        Reply reply;
        ClientContext context;

        request.set_a(21);
        request.set_b(22);

        Status status = stub_->hello_request(&context, request, &reply);

        if (status.ok()) {
            return reply.result();
        } else {
            std::cout << status.error_code() << ": " << status.error_message() << std::endl;
            return 0;
        }
    }

private:
    std::unique_ptr<TestServer::Stub> stub_;

};

int main(int argc, char** argv) {

    GreeterClient greeter(grpc::CreateChannel("127.0.0.1:5000", grpc::InsecureChannelCredentials()));
    std::string user("world");
    int reply = greeter.say_hello(user);
    std::cout << "Greeter received: " << reply << std::endl;

    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.17)

project(grpcdemo)

set(CMAKE_CXX_STANDARD 14)

find_package(Protobuf REQUIRED)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GRPCPP REQUIRED grpc++>=1.22.0)

include_directories(
        ${GRPCPP_INCLUDE_DIRS} # /usr/local/Cellar/grpc/1.29.1/include
        ${Protobuf_INCLUDE_DIRS} # /usr/local/include
)

link_directories(
        ${GRPCPP_LIBRARY_DIRS}
)


add_library(hellolibrary ../protos/helloworld.grpc.pb.cc ../protos/helloworld.pb.cc )

target_link_libraries(hellolibrary
        protobuf::libprotobuf # 将protobuf加到hellolibrary, 因为在hellolibrary 使用了protobuf
    )

add_executable(client_bin main.cpp)

target_link_libraries(client_bin
        ${GRPCPP_LIBRARIES}
        hellolibrary
        )

 

  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,我理解了你的问题。让我们来探讨一下如何使用Java gRPC实现双向流式调用来构建一个简单的流数据分析器。 首先,我们需要定义一个 gRPC 服务。假设我们要构建一个数据分析器,这个服务可以接收一系列数据,并返回一系列数据分析结果。我们可以这样定义这个服务: ``` service DataAnalyzer { // 客户端发送数据流到服务端,并返回分析结果流 rpc Analyze(stream Data) returns (stream Result) {} } // 定义数据和分析结果的消息类型 message Data { string content = 1; } message Result { string analysis = 1; } ``` 接下来,我们需要实现这个服务。我们可以创建一个 Java 类来实现这个服务: ``` public class DataAnalyzerImpl extends DataAnalyzerGrpc.DataAnalyzerImplBase { @Override public StreamObserver<Data> analyze(StreamObserver<Result> responseObserver) { // 创建一个用于处理数据的 StreamObserver StreamObserver<Data> requestObserver = new StreamObserver<Data>() { @Override public void onNext(Data data) { // 处理数据并生成分析结果 Result result = Result.newBuilder() .setAnalysis("Analysis of " + data.getContent()) .build(); // 将分析结果发送给客户端 responseObserver.onNext(result); } @Override public void onError(Throwable t) { // 处理错误 } @Override public void onCompleted() { // 处理完成 responseObserver.onCompleted(); } }; return requestObserver; } } ``` 在这个实现中,我们实现了 `analyze` 方法,它接收一个 `StreamObserver`,并返回一个 `StreamObserver`。我们使用返回的 `StreamObserver` 处理客户端发送的数据。对于每个接收到的数据,我们生成一个分析结果,并将其发送给客户端。 现在我们已经实现了服务端,接下来让我们来实现客户端。我们可以创建一个 Java 类来实现客户端: ``` public class DataAnalyzerClient { public void analyzeData(List<String> data) { // 创建一个用于接收分析结果的 StreamObserver StreamObserver<Result> responseObserver = new StreamObserver<Result>() { @Override public void onNext(Result result) { // 处理分析结果 System.out.println(result.getAnalysis()); } @Override public void onError(Throwable t) { // 处理错误 } @Override public void onCompleted() { // 处理完成 } }; // 创建一个用于发送数据的 StreamObserver StreamObserver<Data> requestObserver = stub.analyze(responseObserver); // 发送数据并等待分析结果 for (String content : data) { Data data = Data.newBuilder() .setContent(content) .build(); requestObserver.onNext(data); } // 完成数据发送 requestObserver.onCompleted(); } } ``` 在这个实现中,我们首先创建两个 `StreamObserver`,一个用于接收分析结果,一个用于发送数据。然后,我们使用 `stub.analyze` 方法获取到一个 `StreamObserver`,并将其传递给用于发送数据的 `StreamObserver`。接着,我们循环发送数据,并等待分析结果。 现在,我们已经实现了一个简单的流数据分析器。我们可以在服务端启动 gRPC 服务器,并在客户端发送一些数据来测试这个分析器。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值