微服务架构简介

微服务是一种将单体应用拆分为独立部署、松耦合的小型服务的架构风格。每个服务专注于单一业务功能,通过轻量级通信机制(如 HTTP/REST、gRPC)交互,可独立开发、部署和扩展。

核心特点:
  1. 单一职责:每个服务解决特定业务问题
  2. 独立部署:服务可单独更新/扩展
  3. 技术异构:不同服务可用不同技术栈
  4. 去中心化治理:服务自治,独立数据库

C++ 微服务示例(使用 REST + JSON)

以下是一个使用 C++ REST SDK (Casablanca) 实现的简单商品查询微服务:

文件结构:
product_service/
├── CMakeLists.txt
├── product_db.hpp
└── main.cpp
代码实现:
  1. 数据库模拟 (product_db.hpp):
#pragma once
#include <map>
#include <string>

struct Product {
    int id;
    std::string name;
    double price;
};

class ProductDB {
public:
    ProductDB() {
        // 模拟数据库初始化
        products_ = {
            {1, {"Laptop", 1299.99}},
            {2, {"Smartphone", 699.50}},
            {3, {"Headphones", 149.99}}
        };
    }

    Product get_product(int id) const {
        auto it = products_.find(id);
        return it != products_.end() ? it->second : Product{0, "Not Found", 0.0};
    }

private:
    std::map<int, Product> products_;
};
  1. 主服务 (main.cpp):
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include "product_db.hpp"

using namespace web;
using namespace web::http;
using namespace web::http::experimental::listener;

class ProductService {
public:
    ProductService(const utility::string_t& url) : listener_(url) {
        listener_.support(methods::GET, 
            std::bind(&ProductService::handle_get, this, std::placeholders::_1));
    }

    void handle_get(http_request request) {
        // 解析URL参数 /product?id=1
        auto query = uri::split_query(request.request_uri().query());
        auto id_param = query.find(U("id"));
        
        if(id_param == query.end()) {
            request.reply(status_codes::BadRequest, U("Missing 'id' parameter"));
            return;
        }

        try {
            int product_id = std::stoi(id_param->second);
            Product product = db_.get_product(product_id);

            json::value response;
            response[U("id")] = product.id;
            response[U("name")] = json::value::string(product.name);
            response[U("price")] = product.price;

            request.reply(status_codes::OK, response);
        } catch(...) {
            request.reply(status_codes::InternalError);
        }
    }

    void start() { listener_.open().wait(); }
    void stop() { listener_.close().wait(); }

private:
    http_listener listener_;
    ProductDB db_;
};

int main() {
    utility::string_t address = U("http://0.0.0.0:8080");
    ProductService service(address);
    
    std::cout << "Starting Product Service at " << address << std::endl;
    service.start();
    
    std::cout << "Press Enter to exit..." << std::endl;
    std::string line;
    std::getline(std::cin, line);
    
    service.stop();
    return 0;
}
  1. CMake 配置 (CMakeLists.txt):
cmake_minimum_required(VERSION 3.10)
project(ProductService)

set(CMAKE_CXX_STANDARD 17)

# 查找依赖
find_package(cpprestsdk REQUIRED)

# 可执行文件
add_executable(product_service main.cpp product_db.hpp)

# 链接库
target_link_libraries(product_service PRIVATE 
    cpprestsdk::cpprest
    cpprestsdk::cpprestsdk_zlib
    cpprestsdk::cpprestsdk_boost_system
    cpprestsdk::cpprestsdk_ssl
    cpprestsdk::cpprestsdk_crypto)

运行步骤:

  1. 安装依赖:

    sudo apt-get install libcpprest-dev libssl-dev
    
  2. 编译项目:

    mkdir build && cd build
    cmake ..
    make
    
  3. 启动服务:

    ./product_service
    # Starting Product Service at http://0.0.0.0:8080
    
  4. 测试服务:

    curl "http://localhost:8080/product?id=2"
    # 输出示例:{"id":2,"name":"Smartphone","price":699.5}
    

微服务通信模式

模式 协议 C++ 实现方案 适用场景
RESTful API HTTP/JSON cpprestsdk, Pistache 公共API,简单交互
gRPC HTTP/2 gRPC C++ 高性能内部通信
消息队列 AMQP RabbitMQ C++ client 异步任务处理

微服务优势与挑战

优势

  • 独立扩展(如商品服务高负载时单独扩容)
  • 技术栈自由(商品服务用C++,用户服务用Go)
  • 故障隔离(库存服务崩溃不影响支付服务)

挑战

  • 分布式事务管理
  • 服务发现与负载均衡
  • 跨服务调试
  • 网络延迟
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐