在 Rust 中通过 REST 参数共享内存数据

Share memory data by REST parameters in Rust

我的 “主要” 文件

mod router;
mod student;

use std::sync::Arc;

use crate::router::init_router;
use crate::router::Memory;

use actix_web::{App, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    dotenv::dotenv().ok();
    let repo = Arc::new(Memory::repository());
    let host = std::env::var("SERVER.HOST").unwrap_or("127.0.0.1".to_string());
    let port = std::env::var("SERVER.PORT").unwrap_or("8080".to_string());
    let url = format!("{}:{}", host, port);
    println!("url: {}", &url);
    
    HttpServer::new(move || {
        App::new()
            .data(repo.clone())     // shared
            .configure(init_router)
    })
    .bind(&url)?
    .run()
    .await
}

我的文件:"router.rs"

use std::sync::Arc;

use crate::student::Student;
use actix_web::{get, web, HttpResponse, Responder};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
pub struct Memory {
    pub students: Vec<Student>,
}

impl Memory {
    fn new() -> Self {
        Memory {
            students: Vec::new(),
        }
    }

    pub fn repository() -> Self{
        Self {
            students: vec![
                {Student::new("1".to_string(), "Daniel".to_string(), 19)},
                {Student::new("2".to_string(), "Lucia".to_string(), 17)},
                {Student::new("3".to_string(), "Juan".to_string(), 14)}
            ]
        }
    }
}

#[get("/studen/list/all")]
async fn list_all(repo: web::Data<Arc<Memory>>) -> impl Responder {
    HttpResponse::Ok().json(repo)
}

pub fn init_router(config: &mut web::ServiceConfig) {
    config.service(list_all);
}

和我的文件:"student.rs"

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
pub struct Student{
    pub id: String,
    pub nombre: String,
    pub calificacion: u32,
}

impl Student{
    pub fn new(id: String, nombre: String, calificacion: u32) -> Self{
        Self{id, nombre, calificacion}
    }
}

所以我想通过以下路径在 json 中显示所有学生:127.0.0.1:3000/student/list/all
但我有以下错误

| HttpResponse::Ok().json(repo)
| ^^^^ the trait Serialize is not implemented for Data<Arc<Memory>>

我仍然无法通过 GET 方法的参数传递此数据,我需要一点帮助才能在 json 中显示它。这是必要的,因为稍后我将需要通过参数添加或删除此数据。

(请注意,您在原始代码中输入的是 #[get("/studen/list/all")] 而不是 #[get("/student/list/all")]。)

您不想将 Data<Arc<Memory>> 序列化为 JSON,您只想序列化 Memory。为此,您可以取消引用 Data<Arc<Memory>> 以获得 Arc<Arc<Memory>>,然后两次取消引用 Arc 以获得 Memory。然后,您添加一个不需要克隆结果 Memory 的引用。所以,你替换

HttpResponse::Ok().json(repo)

HttpResponse::Ok().json(&***repo)

但是,Data 已经是 Arc 的包装器,因此不需要 Arc<Memory>。如果你最终想编辑 Memory,你必须在里面添加一个 Mutex。所以,在序列化它之前,你必须获得对 repo 的锁定。