[Agent] 初始化Agent服务 Rust版

目录

前言

本文基于 Rust + Axum 技术栈,从零完成 Agent 基础 HTTP 服务的搭建,涵盖项目初始化、依赖管理、Web 服务封装、统一响应体设计、健康检查接口实现与服务启动测试全流程。

本项目采用模块化规范开发,结构清晰、可直接作为 Agent 后端服务基础脚手架,可在此基础上扩展路由、业务逻辑、中间件、鉴权、日志等能力。

一、初始化Agent项目

提供两种创建方式,任选其一即可

方式一:快速命令创建

bash 复制代码
cargo new agent

方式二:手动目录初始化(适合有目录的情况)

toml 复制代码
mkdir agent
cargo init ./agent

二、配置项目依赖

方式一:命令行快速添加依赖

bash 复制代码
cargo add axum
cargo add anyhow
cargo add serde -F derive
cargo add serde_json
cargo add tower-http -F trace
cargo add tokio -F full

方式二手动写入Cargo.toml

toml 复制代码
[dependencies]
anyhow = "1.0.102"
axum = "0.8.9"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.150"
tokio = { version = "1.52.3", features = ["full"] }
tower-http = { version = "0.6.11", features = ["trace"] }

三、实现http基础服务

采用模块化拆分,将Web服务启动、路由管理统一封装至app模块,结构解耦,方便后续扩展。

1.创建模块文件

在src目录新建文件lib.rs、app.rs

2.注册模块(lib.rs)

rust 复制代码
/// http服务模块
pub mod app;

3. 封装服务启动逻辑

编辑src/app.rs,实现服务监听、启动、路由初始化基础能力:

rust 复制代码
use anyhow::{Context, Result};
use axum::{Router, serve};
use tokio::net::TcpListener;

/// 启动web服务器
pub async fn start_web() -> Result<()> {
    // 初始化路由
    let app = init_router();
    // 启动服务监听
    let listener = TcpListener::bind("127.0.0.1:8888").await.context("监听端口失败")?;
    // 启动服务
    serve(listener, app).await.context("启动服务失败")
}


/// 初始化路由
fn init_router() -> Router {
    Router::new()
}

四、封装全局统一响应结构体

为保证前后端交互格式统一,封装通用HTTP响应体,支持成功、失败、自定义消息等多种返回场景。

1.创建数据模块

在src中新建文件data.rs,并在lib.rs中注册模块:

rust 复制代码
/// http服务模块
pub mod app;
/// 数据模块
pub mod data;

2.实现通用响应结构体

编辑src/data.rs,完成标准化响应封装:

rust 复制代码
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Resp<T> {
    pub code: u32,
    pub msg: String,
    pub data: Option<T>
}

impl <T> Resp<T> {
    /// 初始化一个响应
    pub fn new(code: u32, msg: String, data: Option<T>) -> Self {
        Self { code, msg, data }
    }
    /// 成功响应
    pub fn ok(data: Option<T>) -> Self {
        Self::new(200, "请求成功".to_string(), data)
    }
    /// 自定义消息的成功响应
    pub fn ok_with_msg(msg: String, data: Option<T>) -> Self {
        Self::new(200, msg, data)
    }
    /// 错误响应
    pub fn error(code: u32, msg: String) -> Self {
        Self::new(code, msg, None)
    }
    /// 带有数据的错误响应
    pub fn error_with_data(code: u32, msg: String, data: Option<T>) -> Self {
        Self::new(code, msg, data)
    }
}

五、实现PING健康检查接口

新增ping接口,用于服务存活探测、健康状态校验。

修改src/app.rs,补充路由注册与接口逻辑:

rust 复制代码
...
/// 初始化路由
fn init_router() -> Router {
    Router::new()
        .route("/ping", get(ping)) // 注册PING接口
}

/// PING接口
async fn ping() -> Json<Resp<String>> {
    Json(Resp::ok(Some("PONG".to_string())))
}

六、服务入口及运行测试

1.配置程序入口

编辑src/main.rs,统一程序启动入口:

rust 复制代码
use agent::app::start_web;
use anyhow::Result;
use tokio::main;

/// 程序入口
#[main]
async fn main() -> Result<()> {
    start_web().await
}

2. 启动服务

bash 复制代码
# debug模式启动
cargo run
# release模式启动
cargo run --release

3.效果验证

服务启动成功后,访问http://127.0.0.1:8888/ping,可正常返回标准化JSON响应,代表基础服务搭建完成。

相关推荐
七夜zippoe11 分钟前
Nexent 知识库:调优靠 Chunk 与重排
开发语言·python·ai智能体·nexent·知识库与rag
kyle~1 小时前
C# --- 反射
开发语言·c#
soso19682 小时前
低功耗设计与BMS开发指南
c语言·开发语言·汇编
Risehuxyc3 小时前
来自PHP项目devnexen的回信
开发语言·php
FRing033 小时前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
我是大猴子4 小时前
分析sss
开发语言
geats人山人海4 小时前
现代c++4.1
java·开发语言·c++
SomeOtherTime4 小时前
第 9 讲:异步并发与 Pin 的底层解剖——async/await 无栈协程状态机脱糖、自引用死锁的终极救赎与 Future/Waker 驱动模型
rust
布莱克6054 小时前
Swift 字符串详解:从基础用法到性能与最佳实践
服务器·开发语言·ssh·字符串·swift
饿了吃洗衣凝珠5 小时前
SELinux
服务器·开发语言·php