1
0
mirror of https://github.com/actix/examples synced 2025-06-26 17:17:42 +02:00

update redis example to v0.22

This commit is contained in:
Rob Ede
2022-10-16 19:14:40 +01:00
parent 99d0afde28
commit fa323545e9
4 changed files with 87 additions and 215 deletions

View File

@ -1,15 +1,13 @@
[package]
name = "actix_redis"
name = "db-redis"
version = "1.0.0"
edition = "2021"
[dependencies]
actix = "0.12"
actix-redis = "0.10"
actix-web = "4"
env_logger = "0.9"
futures-util = { version = "0.3.17", default-features = false, features = ["std"] }
log = "0.4"
redis-async = { version = "0.8", default_features = false, features = ["tokio10"] }
redis = { version = "0.22", default-features = false, features = ["tokio-comp", "connection-manager"] }
serde = { version = "1", features = ["derive"] }

View File

@ -1,8 +1,6 @@
use actix::prelude::*;
use actix_redis::{Command, RedisActor};
use actix_web::{error, middleware, web, App, HttpResponse, HttpServer};
use futures_util::future::try_join_all;
use redis_async::{resp::RespValue, resp_array};
use std::io;
use actix_web::{error, middleware, web, App, HttpResponse, HttpServer, Responder};
use serde::Deserialize;
#[derive(Deserialize)]
@ -13,74 +11,62 @@ pub struct CacheInfo {
}
async fn cache_stuff(
info: web::Json<CacheInfo>,
redis: web::Data<Addr<RedisActor>>,
) -> actix_web::Result<HttpResponse> {
let info = info.into_inner();
let one = redis.send(Command(resp_array!["SET", "mydomain:one", info.one]));
let two = redis.send(Command(resp_array!["SET", "mydomain:two", info.two]));
let three = redis.send(Command(resp_array!["SET", "mydomain:three", info.three]));
// Asynchronously collects the results of the futures given. The returned future will drive
// execution for all of its underlying futures, collecting the results into a destination
// `Vec<RespValue>` in the same order as they were provided. If any future returns an error then
// all other futures will be canceled and an error will be returned immediately. If all futures
// complete successfully, however, then the returned future will succeed with a `Vec` of all the
// successful results.
let res = try_join_all([one, two, three])
web::Json(info): web::Json<CacheInfo>,
redis: web::Data<redis::Client>,
) -> actix_web::Result<impl Responder> {
let mut conn = redis
.get_tokio_connection_manager()
.await
.map_err(error::ErrorInternalServerError)?
.into_iter()
.map(|item| item.map_err(error::ErrorInternalServerError))
.collect::<Result<Vec<_>, _>>()?;
.map_err(error::ErrorInternalServerError)?;
// successful operations return "OK", so confirm that all returned as so
if res
.iter()
.all(|res| matches!(res, RespValue::SimpleString(x) if x == "OK"))
{
let res = redis::Cmd::set_multiple(&[
("my_domain:one", info.one),
("my_domain:two", info.two),
("my_domain:three", info.three),
])
.query_async::<_, String>(&mut conn)
.await
.map_err(error::ErrorInternalServerError)?;
// not strictly necessary, but successful SET operations return "OK"
if res == "OK" {
Ok(HttpResponse::Ok().body("successfully cached values"))
} else {
Ok(HttpResponse::InternalServerError().finish())
}
}
async fn del_stuff(redis: web::Data<Addr<RedisActor>>) -> actix_web::Result<HttpResponse> {
let res = redis
.send(Command(resp_array![
"DEL",
"mydomain:one",
"mydomain:two",
"mydomain:three"
]))
async fn del_stuff(redis: web::Data<redis::Client>) -> actix_web::Result<impl Responder> {
let mut conn = redis
.get_tokio_connection_manager()
.await
.map_err(error::ErrorInternalServerError)?
.map_err(error::ErrorInternalServerError)?;
match res {
RespValue::Integer(x) if x == 3 => {
Ok(HttpResponse::Ok().body("successfully deleted values"))
}
let res = redis::Cmd::del(&["my_domain:one", "my_domain:two", "my_domain:three"])
.query_async::<_, usize>(&mut conn)
.await
.map_err(error::ErrorInternalServerError)?;
_ => {
log::error!("{res:?}");
Ok(HttpResponse::InternalServerError().finish())
}
// not strictly necessary, but successful DEL operations return the number of keys deleted
if res == 3 {
Ok(HttpResponse::Ok().body("successfully deleted values"))
} else {
log::error!("deleted {res} keys");
Ok(HttpResponse::InternalServerError().finish())
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
async fn main() -> io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
log::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(|| {
let redis_addr = RedisActor::start("127.0.0.1:6379");
let redis = redis::Client::open("redis://127.0.0.1:6379").unwrap();
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(redis_addr))
.app_data(web::Data::new(redis.clone()))
.wrap(middleware::Logger::default())
.service(
web::resource("/stuff")
@ -88,6 +74,7 @@ async fn main() -> std::io::Result<()> {
.route(web::delete().to(del_stuff)),
)
})
.workers(2)
.bind(("127.0.0.1", 8080))?
.run()
.await