|
| 1 | +#[macro_use] |
| 2 | +extern crate log; |
| 3 | + |
| 4 | +use rsocket_rust::{error::RSocketError, prelude::*}; |
| 5 | +use rsocket_rust_transport_tcp::TcpServerTransport; |
| 6 | +use std::error::Error; |
| 7 | +use std::sync::Arc; |
| 8 | +use tokio_postgres::{Client as PgClient, NoTls}; |
| 9 | + |
| 10 | +#[tokio::main] |
| 11 | +async fn main() -> Result<(), Box<dyn Error + Send + Sync>> { |
| 12 | + env_logger::builder().format_timestamp_millis().init(); |
| 13 | + let dao = Dao::try_new().await?; |
| 14 | + RSocketFactory::receive() |
| 15 | + .acceptor(Box::new(move |_, _| Ok(Box::new(dao.clone())))) |
| 16 | + .on_start(Box::new(|| info!("server start success!!!"))) |
| 17 | + .transport(TcpServerTransport::from("127.0.0.1:7878")) |
| 18 | + .serve() |
| 19 | + .await |
| 20 | +} |
| 21 | + |
| 22 | +#[derive(Clone)] |
| 23 | +struct Dao { |
| 24 | + client: Arc<PgClient>, |
| 25 | +} |
| 26 | + |
| 27 | +impl RSocket for Dao { |
| 28 | + fn request_response(&self, _: Payload) -> Mono<Result<Payload, RSocketError>> { |
| 29 | + let client = self.client.clone(); |
| 30 | + Box::pin(async move { |
| 31 | + let row = client |
| 32 | + .query_one("SELECT 'world' AS hello", &[]) |
| 33 | + .await |
| 34 | + .expect("Execute SQL failed!"); |
| 35 | + let result: String = row.get("hello"); |
| 36 | + Ok(Payload::builder().set_data_utf8(&result).build()) |
| 37 | + }) |
| 38 | + } |
| 39 | + |
| 40 | + fn metadata_push(&self, _: Payload) -> Mono<()> { |
| 41 | + unimplemented!() |
| 42 | + } |
| 43 | + |
| 44 | + fn fire_and_forget(&self, _: Payload) -> Mono<()> { |
| 45 | + unimplemented!() |
| 46 | + } |
| 47 | + |
| 48 | + fn request_stream(&self, _: Payload) -> Flux<Result<Payload, RSocketError>> { |
| 49 | + unimplemented!() |
| 50 | + } |
| 51 | + |
| 52 | + fn request_channel( |
| 53 | + &self, |
| 54 | + _: Flux<Result<Payload, RSocketError>>, |
| 55 | + ) -> Flux<Result<Payload, RSocketError>> { |
| 56 | + unimplemented!() |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +impl Dao { |
| 61 | + async fn try_new() -> Result<Dao, Box<dyn Error + Sync + Send>> { |
| 62 | + let (client, connection) = |
| 63 | + tokio_postgres::connect("host=localhost user=postgres password=postgres", NoTls) |
| 64 | + .await?; |
| 65 | + |
| 66 | + // The connection object performs the actual communication with the database, |
| 67 | + // so spawn it off to run on its own. |
| 68 | + tokio::spawn(async move { |
| 69 | + if let Err(e) = connection.await { |
| 70 | + eprintln!("connection error: {}", e); |
| 71 | + } |
| 72 | + }); |
| 73 | + |
| 74 | + info!("==> create postgres pool success!"); |
| 75 | + Ok(Dao { |
| 76 | + client: Arc::new(client), |
| 77 | + }) |
| 78 | + } |
| 79 | +} |
0 commit comments