一、安装

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(hellolibraryprotobuf::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 timeclass HelloBusiness(object):def __init__(self):super(HelloBusiness, self).__init__()self.ip = "127.0.0.1"self.port = 5000self.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 Nonedef hello_business(self, msg):""":param msg: request msg:return:"""proto_data = helloworld_pb2.HelloMessage()  #ParseDict(msg, proto_data)  # 格式化msgresponse = self.client.hello_request.future(proto_data)  # 向server发送数据response.add_done_callback(self.hello_callback)  # 回调函数, 发送数据使用异步[future]时, 必须加回调函数return responsedef 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 Nonegrpc_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"
#endifusing 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(hellolibraryprotobuf::libprotobuf # 将protobuf加到hellolibrary, 因为在hellolibrary 使用了protobuf)add_executable(client_bin main.cpp)target_link_libraries(client_bin${GRPCPP_LIBRARIES}hellolibrary)

gRPC编译和安装——Linux版相关推荐

  1. linux libimf.so,如何安装Linux版FLOW-3D及注意事项

    安装Linux版的flow3d流程: 1.复制flow3d安装CD盘中unix文件夹到Linux系统桌面:(或从CD中直接安装也可以) 2.从terminal进入unix文件夹: 3../instal ...

  2. linux离线安装redmine_举个栗子!Tableau 技巧(97):离线安装 Linux 版 Tableau Server...

    为什么需要离线安装? 实际企业应用中,我们的服务器计算机基于数据保密.数据安全的需求下,使用的网络环境是内部网络,无法访问外部 Internet .这种情况,安装.停用.迁移或升级 Tableau S ...

  3. 3dmax linux版本,[转载]如何安装Linux版FLOW-3D及注意事项

    安装linux版的flow3d流程: 1.复制flow3d安装CD盘中unix文件夹到linux系统桌面:(或从CD中直接安装也可以) 2.从terminal进入unix文件夹: 3../instal ...

  4. linux网卡驱动程序的编译与安装,linux网卡驱动程序的编译与安装

    安装实例 linux网卡驱动程序的编译与安装 powered by KindGeorge 一般来说,目前新版的 Linux 预设可以支持的网络卡芯片组数量已经很完备了,很多网络卡芯片都已经被支持, 例 ...

  5. ubuntu18.04安装linux版的有道词典

    一直在ubuntu上安装有道词典,因为有道还是很好用的,但是发现有道linux版有多个版本,一时不知道如何选择: https://cidian.youdao.com/multi.html 我的ubun ...

  6. linux 先编译 再安装,Linux下编译安装FFmpeg

    官网介绍 FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stre ...

  7. 安装Linux版的Notepad++

    安装: 1,打开终端,ctrl+T 2,输入命令: sudo add-apt-repository ppa:notepadqq-team/notepadqq//添加安装包 sudo apt-get u ...

  8. 安装linux版的skype

    要国外的源 axel https://go.skype.com/skypeforlinux-64.deb dpkg -i xxxx.deb

  9. 网易云音乐linux安装路径,修复网易云音乐Linux版不能安装及运行的问题

    安装Linux版网易云音乐,运行后不出现界面的,试试以下几种方案 1.先删除 $HOME/.cache/netease-cloud-music,试运行,如果成功了,后面的就不用看了. rm $HOME ...

最新文章

  1. PCL_common模块api代码解析
  2. 使用fbs打包pyqt5本人亲自尝试过的
  3. CSS的优先级和继承性
  4. 【瞎扯】About Me
  5. android XMl 解析神奇xstream 二: 把对象转换成xml
  6. mysql 将查询所得结果集的某一字段拼接成字符串
  7. [翻译] .NET Core 3.0 Preview 9 发布
  8. xmapp 查询文字内容显示乱码
  9. CV新赛事|CT影像诊断新冠肺炎北京垃圾分类识别~文末有福利
  10. ReactJs 第二章 JSX
  11. iOS学习笔记-自己动手写RESideMenu
  12. MaterialDesign之NavigationView和DrawerLayout实现侧滑菜单栏
  13. 便携式办公套件LibreOffice Portable 4.0.1
  14. IQC来料检验平台开发部署(集成金蝶K3待检数据生成功能)
  15. Pigsty是什么?
  16. OpenGL学习小结
  17. 简单合并word文档(转)
  18. ​万邦医药在创业板过会:上半年收入约1亿元,陶春蕾母子为实控人​
  19. JavaScript/HTML格式化
  20. 国内免费(开源)CMS系统【大全】

热门文章

  1. 【Computer Organization笔记06】浮点数的数据表示,浮点数加减运算
  2. 集算器协助MongoDB计算之交叉汇总
  3. 基于FPGA实现uart串口模块(Verilog)--------发送模块及整合
  4. The Most Important Skill for Software Architects
  5. JAVA获取同一路径下所有子类或接口实现类
  6. VSCode 中,TS 提示 ”无法找到 *.vue 声明文件“ 的解决方案
  7. 快速删除大文件 多级目录 同步并删除 rsync
  8. iconv命令的使用,解决libxml2中解释中文失败的问题
  9. 我想批量删除专题内最古老的100篇文章
  10. GDAL中的SURF算法