rust 编写hello world redis

Posted 柳清风09

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rust 编写hello world redis相关的知识,希望对你有一定的参考价值。

服务端代码

use mini_redis::Connection, Frame;
use tokio::net::TcpListener, TcpStream;
use std::sync::Arc,Mutex;
use std::collections::HashMap;
use bytes::Bytes;


type Db = Arc<Mutex<HashMap<String, Bytes>>>;


#[tokio::main]
pub async fn main() 
    let mut listener = TcpListener::bind("127.0.0.1:6379").await.unwrap();

    let data = Arc::new(Mutex::new(HashMap::new()));
    loop
        println!("start server");
        let (stream, _) = listener.accept().await.unwrap();
        let db :Db = data.clone();
        tokio::spawn(
            async move
                process(stream,db).await;
            
        );
    


async fn process(stream: TcpStream,db: Db)

    use mini_redis::Command::self, Get, Set;

   let mut conn =  Connection::new(stream);
    while let Some(frame) = conn.read_frame().await.unwrap()
        println!("GOT: :?", frame);
        let response = match Command::from_frame(frame).unwrap()
            Get(cmd)=>
                let data = db.lock().unwrap();
                 if let Some(d ) =  data.get(cmd.key()) 
                    Frame::Bulk(d.clone())
                else
                     Frame::Null
                 
            
            Set(cmd)=>
                let mut data = db.lock().unwrap();
                data.insert(cmd.key().to_string(),cmd.value().clone());
                Frame::Simple("OK".to_string())
            
            cmd => panic!("unimplemented :?", cmd),
        ;

        conn.write_frame(&response).await;
    

依赖三个库

[dependencies]
tokio = version = "0.2", features = ["full"]
mini-redis = "0.2"
bytes = "0.5"

客户端代码

use mini_redis::client, Result;

#[tokio::main]
pub async fn main() -> Result<()> 
    let mut c = client::connect("127.0.0.1:6379").await.unwrap();
    c.set("hello", "world".into()).await?;
    println!("write success");
    let result = c.get("hello").await?;
    println!("got value from the server; result=:?", result);

    Ok(())
```

以上是关于rust 编写hello world redis的主要内容,如果未能解决你的问题,请参考以下文章

rust 编写hello world redis

使用rust编写helloworld项目

Rust hello world !

Rust hello world 语法讲解

Rust hello world 语法解说

00_Rust安装及Hello World