无法从流中读取redis请求

k7fdbhmy  于 12个月前  发布在  Redis
关注(0)|答案(1)|浏览(131)

我有以下代码从网络请求中读取:

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let req: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();

    println!("Request: {:#?}", req);
}

字符串
这与预期的http请求一样。
但是对于一个redis请求,比如'redis-calling ping',它不能读取和超时。
我犯了什么错?

lymgl2op

lymgl2op1#

Redis使用一种名为RESP(REdis Serialization Protocol)的协议,这是一种二进制安全的协议,旨在序列化数据结构。它不像HTTP那样只是纯文本,所以简单地从TCP流中阅读行并不总是能正确地执行Redis命令。

use std::io::{self, BufRead, BufReader};
use std::net::TcpStream;

fn handle_connection(mut stream: TcpStream) {
    let mut buf_reader = BufReader::new(&mut stream);

    loop {
        let mut line = String::new();
        match buf_reader.read_line(&mut line) {
            Ok(0) => break, // End of stream
            Ok(_) => {
                if line.starts_with("*") {
                    // Handle Redis command
                    // You will need to implement proper RESP parsing here
                    println!("Redis command: {}", line.trim());
                } else {
                    // Not a Redis command or end of command
                    break;
                }
            }
            Err(e) => {
                eprintln!("Failed to read from stream: {}", e);
                break;
            }
        }
    }
}

字符串
请查看:https://redis.io/docs/reference/protocol-spec/#:~:text= num%20is%20essentially%20a%20serialization,an%20array%20of%20bulk%20strings.

相关问题