1
0
mirror of https://github.com/actix/examples synced 2025-06-28 18:00:37 +02:00

Database interactions/redis (#524)

Co-authored-by: Rob Ede <robjtede@icloud.com>
This commit is contained in:
Christopher Gubbin
2022-02-15 00:35:00 +00:00
committed by GitHub
parent 7ea3f7f54a
commit 5c1e25fe52
4 changed files with 158 additions and 353 deletions

View File

@ -1,7 +1,7 @@
use actix::prelude::*;
use actix_redis::{Command, RedisActor};
use actix_web::{middleware, web, App, Error as AWError, HttpResponse, HttpServer};
use futures::future::join_all;
use actix_web::{error, middleware, web, App, HttpResponse, HttpServer};
use futures_util::future::try_join_all;
use redis_async::{resp::RespValue, resp_array};
use serde::Deserialize;
@ -15,42 +15,40 @@ pub struct CacheInfo {
async fn cache_stuff(
info: web::Json<CacheInfo>,
redis: web::Data<Addr<RedisActor>>,
) -> Result<HttpResponse, AWError> {
) -> 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]));
// Creates a future which represents a collection of 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: Vec<Result<RespValue, AWError>> =
join_all(vec![one, two, three].into_iter())
.await
.into_iter()
.map(|item| {
item.map_err(AWError::from)
.and_then(|res| res.map_err(AWError::from))
})
.collect();
// 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])
.await
.map_err(error::ErrorInternalServerError)?
.into_iter()
.map(|item| item.map_err(error::ErrorInternalServerError))
.collect::<Result<Vec<_>, _>>()?;
// successful operations return "OK", so confirm that all returned as so
if !res
if res
.iter()
.all(|res| matches!(res,Ok(RespValue::SimpleString(x)) if x == "OK"))
.all(|res| matches!(res, RespValue::SimpleString(x) if x == "OK"))
{
Ok(HttpResponse::InternalServerError().finish())
} else {
Ok(HttpResponse::Ok().body("successfully cached values"))
} else {
Ok(HttpResponse::InternalServerError().finish())
}
}
async fn del_stuff(redis: web::Data<Addr<RedisActor>>) -> Result<HttpResponse, AWError> {
async fn del_stuff(
redis: web::Data<Addr<RedisActor>>,
) -> actix_web::Result<HttpResponse> {
let res = redis
.send(Command(resp_array![
"DEL",
@ -58,14 +56,17 @@ async fn del_stuff(redis: web::Data<Addr<RedisActor>>) -> Result<HttpResponse, A
"mydomain:two",
"mydomain:three"
]))
.await?;
.await
.map_err(error::ErrorInternalServerError)?
.map_err(error::ErrorInternalServerError)?;
match res {
Ok(RespValue::Integer(x)) if x == 3 => {
RespValue::Integer(x) if x == 3 => {
Ok(HttpResponse::Ok().body("successfully deleted values"))
}
_ => {
println!("---->{:?}", res);
log::error!("{:?}", res);
Ok(HttpResponse::InternalServerError().finish())
}
}
@ -73,14 +74,15 @@ async fn del_stuff(redis: web::Data<Addr<RedisActor>>) -> Result<HttpResponse, A
#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=trace,actix_redis=trace");
env_logger::init();
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");
App::new()
.data(redis_addr)
.app_data(web::Data::new(redis_addr))
.wrap(middleware::Logger::default())
.service(
web::resource("/stuff")
@ -88,7 +90,7 @@ async fn main() -> std::io::Result<()> {
.route(web::delete().to(del_stuff)),
)
})
.bind("0.0.0.0:8080")?
.bind(("127.0.0.1", 8080))?
.run()
.await
}