|
| 1 | +use redis::Client as RedisClient; |
| 2 | +use rsocket_rust::{error::RSocketError, prelude::*}; |
| 3 | +use rsocket_rust_transport_tcp::TcpServerTransport; |
| 4 | +use std::error::Error; |
| 5 | +use std::str::FromStr; |
| 6 | + |
| 7 | +#[derive(Clone)] |
| 8 | +struct RedisDao { |
| 9 | + inner: RedisClient, |
| 10 | +} |
| 11 | + |
| 12 | +#[tokio::main] |
| 13 | +async fn main() -> Result<(), Box<dyn Error + Send + Sync>> { |
| 14 | + let dao = RedisDao::from_str("redis://127.0.0.1").expect("Connect redis failed!"); |
| 15 | + RSocketFactory::receive() |
| 16 | + .acceptor(Box::new(move |_setup, _socket| Ok(Box::new(dao.clone())))) |
| 17 | + .transport(TcpServerTransport::from("127.0.0.1:7878")) |
| 18 | + .serve() |
| 19 | + .await |
| 20 | +} |
| 21 | + |
| 22 | +impl FromStr for RedisDao { |
| 23 | + type Err = redis::RedisError; |
| 24 | + |
| 25 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 26 | + let client = redis::Client::open(s)?; |
| 27 | + Ok(RedisDao { inner: client }) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +impl RSocket for RedisDao { |
| 32 | + fn request_response(&self, req: Payload) -> Mono<Result<Payload, RSocketError>> { |
| 33 | + let client = self.inner.clone(); |
| 34 | + |
| 35 | + Box::pin(async move { |
| 36 | + let mut conn: redis::aio::Connection = client |
| 37 | + .get_async_connection() |
| 38 | + .await |
| 39 | + .expect("Connect redis failed!"); |
| 40 | + let value: String = redis::cmd("GET") |
| 41 | + .arg(&[req.data_utf8()]) |
| 42 | + .query_async(&mut conn) |
| 43 | + .await |
| 44 | + .unwrap_or("<nil>".to_owned()); |
| 45 | + Ok(Payload::builder().set_data_utf8(&value).build()) |
| 46 | + }) |
| 47 | + } |
| 48 | + |
| 49 | + fn metadata_push(&self, _req: Payload) -> Mono<()> { |
| 50 | + unimplemented!() |
| 51 | + } |
| 52 | + fn fire_and_forget(&self, _req: Payload) -> Mono<()> { |
| 53 | + unimplemented!() |
| 54 | + } |
| 55 | + fn request_stream(&self, _req: Payload) -> Flux<Result<Payload, RSocketError>> { |
| 56 | + unimplemented!() |
| 57 | + } |
| 58 | + fn request_channel( |
| 59 | + &self, |
| 60 | + _reqs: Flux<Result<Payload, RSocketError>>, |
| 61 | + ) -> Flux<Result<Payload, RSocketError>> { |
| 62 | + unimplemented!() |
| 63 | + } |
| 64 | +} |
0 commit comments