examples icon indicating copy to clipboard operation
examples copied to clipboard

Example of redis subscribe/psubscribe

Open 0x8f701 opened this issue 5 years ago • 7 comments

Hello guys, is there a way to use redis subscribe/psubscribe in actix + actix-web system?

I don't want to create a seperate thread for handling this, is there a better way to do this?

0x8f701 avatar Feb 17 '20 21:02 0x8f701

See also: https://github.com/actix/actix-redis/issues/20

0x8f701 avatar Feb 17 '20 21:02 0x8f701

@GopherJ actix-redis publish example

use actix::Addr;
use redis_async::resp_array;
use actix_redis::{Command, RedisActor};
use actix_web::{middleware, web, App, HttpResponse, HttpServer};

#[actix_web::get("/")]
async fn cache_stuff(
  redis: web::Data<Addr<RedisActor>>
) -> HttpResponse {
  let datetime_now: String = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
  let _future = redis.send(Command(resp_array!["PUBLISH", "test", datetime_now.as_str()])).await;
  HttpResponse::Ok().body(format!("successfully publish {message} to `test` channel", message = datetime_now))
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
  std::env::set_var("RUST_LOG", "actix_web=trace,actix_redis=trace");
  env_logger::init();

  HttpServer::new(|| {
    App::new()
      .data(RedisActor::start("127.0.0.1:6379"))
      .wrap(middleware::Logger::default())
      .service(cache_stuff)
  })
    .bind("0.0.0.0:8080")?
    .run()
    .await
}

[dependencies]
actix = "*"
actix-rt = "*"
actix-web = "*"
actix-redis = "*"
redis-async = "*"
env_logger = "*"

pymongo avatar May 01 '20 10:05 pymongo

@pymongo hello, what's really needed is subscribe and psubscribe

0x8f701 avatar May 01 '20 12:05 0x8f701

@GopherJ I guess there is no redis sub/pub API in actix-redis.

actix-redis depend on redis-async,

you can check out pubsub example in redis-async/examples/pubsub.rs

pymongo avatar May 04 '20 13:05 pymongo

@pymongo I already checked them before creating this issue and that's also why I created this issue, because we should have a way to subscribe/publish.

0x8f701 avatar May 04 '20 15:05 0x8f701

I also encounter this problem. Is there a plan to improve it? @robjtede

shanliu avatar May 02 '22 07:05 shanliu

@GopherJ
Have you solved this problem

shanliu avatar May 02 '22 07:05 shanliu