Pass redis connection to HttpProxy #478
-
Hi guys, I've just started learning Rust, and I am trying to rewrite our reverse proxy written with Go in Rust using Pingora. When I pass the connection inside my Proxy struct and try to use it inside the "early_request_filter" function, it complains that "&self" is not mutable, which is not in the function signature. I'm definitely missing something here. I would appreciate your help. Example:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You had issues because you tried to mutate a Redis connection stored in &self. Switching to deadpool-redis fixed that by letting you grab a connection dynamically. Here’s the fix: Cargo.toml: [package]
name = "pi"
version = "0.1.0"
edition = "2021"
[dependencies]
async-trait = "0.1.83"
deadpool-redis = "0.18.0"
pingora = { version = "0.4.0", features = ["lb"] } main.rs: use async_trait::async_trait;
use deadpool_redis::{redis::cmd, Config, Pool, Runtime};
use pingora::prelude::*;
pub struct Proxy {
pool: Pool,
}
impl Proxy {
fn new() -> Self {
let cfg = Config::from_url("redis://127.0.0.1:6379");
let pool = cfg.create_pool(Some(Runtime::Tokio1)).unwrap();
Self { pool }
}
}
#[async_trait]
impl ProxyHttp for Proxy {
type CTX = ();
fn new_ctx(&self) -> Self::CTX {
()
}
async fn early_request_filter(&self, _session: &mut Session, _ctx: &mut Self::CTX) -> Result<()>
where
Self::CTX: Send + Sync,
{
let mut conn = self.pool.get().await.unwrap();
cmd("SET")
.arg(&["foo", "bar"])
.query_async::<()>(&mut conn)
.await
.expect("Failed to set key in Redis");
println!("Saved");
Ok(())
}
async fn upstream_peer(&self, _session: &mut Session, _ctx: &mut ()) -> Result<Box<HttpPeer>> {
todo!()
}
}
fn main() {
let mut my_server = Server::new(None).unwrap();
my_server.bootstrap();
let proxy_instance = Proxy::new();
let mut proxy = http_proxy_service(&my_server.configuration, proxy_instance);
proxy
.add_tls("0.0.0.0:443", "cert/certificate.crt", "cert/private.key")
.unwrap();
my_server.add_service(proxy);
my_server.run_forever();
} |
Beta Was this translation helpful? Give feedback.
You had issues because you tried to mutate a Redis connection stored in &self. Switching to deadpool-redis fixed that by letting you grab a connection dynamically. Here’s the fix:
Cargo.toml:
main.rs: