Ubuntu快速安装使用gRPC C++

目录

  • 引言
  • 一、快速安装
    • 1. 安装必要依赖库
    • 2. 安装gRPC
  • 二、测试使用
  • 三、参考博客

引言

关于gRPC随着云原生微服务的火热也流行了起来,而且学好一个gRPC框架对目前来说也是必须的了。然而对于一个基础的小白来说,这个gRPC的框架运用起来是及其的困难,具体体现在依赖库繁多,且大部分需要对git进行代理,在实际运用框架时,常常会发现某些库或者头文件找不到了,常常是些编译链接错误,还是很烦的。本篇文章通过博主自己整理的非常简单的操作来让新手小白进行一个友好的入门,并且对于博主自己也是一个笔记的作用,并且对于一些用到的第三方库也给出了百度网盘的链接,跟着步骤来还是很容易上手的,也没什么废话,跟着教程实操起来吧!

一、快速安装

安装所需要的第三方库-百度网盘链接

1. 安装必要依赖库

执行以下命令安装

sudo apt update
sudo apt-get update
sudo apt install -y protobuf-compiler libprotobuf-dev  # 安装protobuf编译器和库
sudo apt install -y build-essential autoconf libtool pkg-config libsystemd-dev libssl-dev  # 安装依赖项
sudo apt install -y libgflags-dev libgtest-dev libc++-dev clang cmake # 安装c++支持
sudo apt-get install autoconf automake libtool  # 依赖工具

2. 安装gRPC

安装gRPC需要的第三方库-百度网盘链接

tar -jxf grpc-v1.45.2.tar.bz2
cd grpc-v1.45.2 
mkdir -p cmake/build
cd cmake/build
cmake ../..
make -j 4
sudo make install  # 安装到系统目录

二、测试使用

先运行以下命令创建测试文件,然后将文件中的内容填充到对应的文件里

mkdir gRPC-test
cd gRPC-test
touch client.cc  CMakeLists.txt  helloworld.proto  server.cc

helloworld.proto

syntax = "proto3";package helloworld;service Greeter {rpc SayHello (HelloRequest) returns (HelloResponse) {}
}message HelloRequest {string name = 1;
}message HelloResponse {string message = 1;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)project(helloworld)set(CMAKE_CXX_STANDARD 17)set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR})# 查找 Protobuf 库
find_package(Protobuf CONFIG REQUIRED)
find_package(gRPC CONFIG REQUIRED)# 添加 server 可执行程序
add_executable(server server.cc helloworld.grpc.pb.cc helloworld.pb.cc
)
# 添加对 protobuf 和 gRPC 库的链接
target_link_libraries(server PRIVATE gRPC::grpc++  # CMake 提供的目标库名称gRPC::grpc++_reflection  # CMake 提供的目标库名称protobuf::libprotobuf  # CMake 提供的目标库名称
)# 添加 client 可执行程序
add_executable(client client.cc helloworld.grpc.pb.cc helloworld.pb.cc
)
# 添加对 protobuf 和 gRPC 库的链接
target_link_libraries(client PRIVATEgRPC::grpc++gRPC::grpc++_reflectionprotobuf::libprotobuf
)

server.cc

#include <iostream>
#include <memory>
#include <string>#include <grpcpp/grpcpp.h>
#include "helloworld.grpc.pb.h"using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloRequest;
using helloworld::HelloResponse;// Logic and data behind the server's behavior.
class GreeterServiceImpl final : public Greeter::Service {Status SayHello(ServerContext* context, const HelloRequest* request,HelloResponse* reply) override {std::string prefix("Hello ");reply->set_message(prefix + request->name());return Status::OK;}
};void RunServer() {std::string server_address("0.0.0.0:50051");GreeterServiceImpl service;ServerBuilder builder;// Listen on the given address without any authentication mechanism.builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());// Register "service" as the instance through which we'll communicate with// clients. In this case it corresponds to an *synchronous* service.builder.RegisterService(&service);// Finally assemble the server.std::unique_ptr<Server> server(builder.BuildAndStart());std::cout << "Server listening on " << server_address << std::endl;// Wait for the server to shutdown. Note that some other thread must be// responsible for shutting down the server for this call to ever return.server->Wait();
}int main(int argc, char** argv) {RunServer();return 0;
}

client.cc

#include <iostream>
#include <memory>
#include <string>#include <grpcpp/grpcpp.h>
#include "helloworld.grpc.pb.h"using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloRequest;
using helloworld::HelloResponse;class GreeterClient {public:GreeterClient(std::shared_ptr<Channel> channel): stub_(Greeter::NewStub(channel)) {}// Assembles the client's payload, sends it and presents the response back// from the server.std::string SayHello(const std::string& user) {// Data we are sending to the server.HelloRequest request;request.set_name(user);// Container for the data we expect from the server.HelloResponse reply;// Context for the client. It could be used to convey extra information to// the server and/or tweak certain RPC behaviors.ClientContext context;// The actual RPC.Status status = stub_->SayHello(&context, request, &reply);// Act upon its status.if (status.ok()) {return reply.message();} else {std::cout << status.error_code() << ": " << status.error_message()<< std::endl;return "RPC failed";}}private:std::unique_ptr<Greeter::Stub> stub_;
};int main(int argc, char** argv) {// Instantiate the client. It requires a channel, out of which the actual RPCs// are created. This channel models a connection to an endpoint specified by// the argument "--target=" which is the only expected argument.// We indicate that the channel isn't authenticated (use of// InsecureChannelCredentials()).std::string target_str;std::string arg_str("--target");if (argc > 1) {std::string arg_val = argv[1];size_t start_pos = arg_val.find(arg_str);if (start_pos != std::string::npos) {start_pos += arg_str.size();if (arg_val[start_pos] == '=') {target_str = arg_val.substr(start_pos + 1);} else {std::cout << "The only correct argument syntax is --target=" << std::endl;return 0;}} else {std::cout << "The only acceptable argument is --target=" << std::endl;return 0;}} else {target_str = "localhost:50051";}GreeterClient greeter(grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));std::string user("world");std::string reply = greeter.SayHello(user);std::cout << "Greeter received: " << reply << std::endl;return 0;
}

执行以下命令进行编译生成可执行程序

protoc -I=. --grpc_out=./ --cpp_out=./ --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` ./helloworld.proto  # 生成.pb.h .pb.cc .grpc.pb.h .grpc.pb.cc
mkdir build
cd build
cmake ..  # 生成Makefile文件
make  # 编译

然后打开两个终端运行程序,出现如下图说明已经测试成功啦

./server  # 第一个shell
./client  # 第二个shell

在这里插入图片描述

三、参考博客

参考博客-知乎
参考博客-CSDN

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/73675.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

高数1.5 极限的运算法则

1. 预备知识 2.四则求极限法则 3.复合运算求极限法则

Python中的“泛型”和“多重继承”

“泛型”和“多重继承”属于 Python 的语法规则。 1. 泛型&#xff08;Generic[T]&#xff09; 通俗解释 泛型允许你在定义类或函数时&#xff0c;不指定具体的类型&#xff0c;而是使用一个“占位符”&#xff08;通常命名为 T&#xff09;。这就像你制作一个盒子&#xff0…

pandas学习笔记(一)——基础知识和应用案例

pandas学习笔记 基础语法参考菜鸟教程&#xff1a;https://www.runoob.com/pandas/pandas-tutorial.html # jupyter import pandas as pd import matplotlib from matplotlib import pyplot as plt import numpy as npmatplotlib.use(TkAgg)data {timestamp: [1, 2, 3, 4, 5…

海绵音乐 3.4.0 | 免费AI音乐创作软件,支持多种风格智能生成

海绵音乐是一款专为Android用户设计的免费AI音乐创作软件&#xff0c;搭载深度神经网络作曲引擎&#xff0c;支持流行、电子、古风等12种音乐风格智能生成。提供多轨道编辑界面&#xff08;8轨同步混音&#xff09;&#xff0c;可自定义鼓点、旋律和和弦进行实时混音&#xff0…

2025 香港 Web3 嘉年华:全球 Web3 生态的年度盛会

自 2023 年首届香港 Web3 嘉年华成功举办以来&#xff0c;这一盛会已成为全球 Web3 领域规模最大、影响力最深远的行业活动之一。2025 年 4 月 6 日至 9 日&#xff0c;第三届香港 Web3 嘉年华将在香港盛大举行。本届活动由万向区块链实验室与 HashKey Group 联合主办、W3ME 承…

【Dify平台】Function Call 模式模式和ReAct模型有什么不同?

本文原创作者:姚瑞南 AI-agent 大模型运营专家,先后任职于美团、猎聘等中大厂AI训练专家和智能运营专家岗;多年人工智能行业智能产品运营及大模型落地经验,拥有AI外呼方向国家专利与PMP项目管理证书。(转载需经授权) 目录 1. DIFY 平台的 Function Call 模式 2. ReAct…

解决 React Native 0.76 中 com.facebook.react.settings 插件缺失问题

在使用 React Native 0.76 创建项目时&#xff0c;遇到以下错误&#xff1a; FAILURE: Build failed with an exception. * Where: Settings file /Users/wangxp/learn/AwesomeProject/android/settings.gradle line: 2 * What went wrong: Plugin [id: com.facebook.react.se…

Linux目录结构以及文件操作

Linux目录结构以及文件操作 ubuntu属于Linux的发行版&#xff0c;带图形界面。但是跑在嵌入式设备中的Linux操作系统往往不带图形界面&#xff0c;直接使用命令来操作。Linux区分大小写。 在Linux系统上&#xff0c;文件被看作字节序列。 普通文件&#xff08;—&#xff09…

React19源码系列之FiberRoot节点和Fiber节点

在上一篇文章&#xff0c;看了createRoot函数的大致流程。 createContainer函数创建并返回了FiberRoot 。FiberRoot是由createFiberRoot函数创建&#xff0c; createFiberRoot函数还将 FiberRoot和 根Fiber 通过current属性建立起了联系。将FiberRoot作为参数传给 ReactDOMRoo…

vue3+antd+a-menu配置

antd是用的3版本 <a-menu v-model:selectedKeys"selectedKeys" mode"inline" click"toPage"><template v-for"i in menus"><a-menu-item v-if"!i.children" :key"i.path"><span>{{ i.nam…

【2025年3月最新】Cities_Skylines:城市天际线1全DLC解锁下载与教程

亲测2025年3月11日能用&#xff0c;能解锁全部DLC 使用教程 点击下载 点击下载

基于Django的交通指示图像识别分析系统

【Django】基于Django的交通指示图像识别分析系统 &#xff08;完整系统源码开发笔记详细部署教程&#xff09;✅ 目录 一、项目简介二、项目界面展示三、项目视频展示 一、项目简介 本项目旨在通过大量交通标志数据训练后&#xff0c;得到较好的识别模型&#xff0c;便于用户…

SAP HANA on AWS Amazon Web Services

SAP HANA on AWS Amazon Web Services

【设计模式】】工厂模式

三、工厂模式 3.1 工厂模式 创建一个类对象的传统方式是使用关键字new, 因为用new 创建的类对象是一个堆对象&#xff0c;可以实现多态。工厂模式通过把创建对象的代码包装起来&#xff0c;实现创建对象的代码与具体 的业务逻辑代码相隔离的目的(将对象的创建和使用进行解耦)…

单片机外设快速入门篇(五)——GPIO篇

文章目录 一、GPIO输入模式​二.GPIO输出模式三.GPIO配置步骤 一、GPIO输入模式 ​1. 浮空输入&#xff08;Floating Input&#xff09;​ ​原理&#xff1a;引脚电平完全由外部电路决定&#xff0c;无内部上拉或下拉电阻。 ​特点&#xff1a; 悬空时电平不确定&#xff08;…

Python递归与递推的练习(初步了解复杂度,全排列的价值,奇妙的变换,数正方形,高塔登顶方案)

一.了解复杂度 1.1 为什么要考虑复杂度 在比赛中&#xff0c;编程题会有时间和空间的限制&#xff0c;所以我们需要根据时间复杂度和空间复杂度来判断用什么样的算法。 在本章中递归的时间复杂度比递推慢好多所有我们在写代码时对递归和递推的选择中应该尽量考虑递推。 复杂度…

解决分布式事务的方案 —— Seata

解决分布式事务的方案 —— Seata 1. 认识 Seata 解决分布式事务的方案有很多&#xff0c;但实现起来都比较复杂&#xff0c;因此我们一般会使用开源的框架来解决分布式事务问题。在众多的开源分布式事务框架中&#xff0c;功能最完善、使用最多的就是阿里巴巴在 2019 年开源…

Antd实现上传下载csv文件

1 上传 解析csv文件&#xff1a; import { parse } from papaparse;export function parseCSV(file: File): Promise<string[][]> {return new Promise((resolve, reject) > {const reader new FileReader();reader.onload () > {const csvData reader.result…

Asp.net Core API 本地化

本文是一个demo&#xff0c;演示了如何根据用户接口查询字段(正常放header中),设置当前culture&#xff0c;并获取当前culture的key value给用户提示 创建Resources文件夹&#xff0c;添加以下三个文件 其中ExceptionUnuse 是一个空的类&#xff0c;供IStringLocalizer使用&a…

MambaVision:一种Mamba-Transformer混合视觉骨干网络

摘要 我们提出了一种新型混合Mamba-Transformer主干网络&#xff0c;称为MambaVision&#xff0c;该网络专为视觉应用而设计。我们的核心贡献包括重新设计Mamba公式&#xff0c;以增强其对视觉特征的高效建模能力。此外&#xff0c;我们还对将视觉Transformer&#xff08;ViT&…