#actix #storage #web #async

actix-storage

General key value storage for actix-web

2 releases

0.1.1 Nov 4, 2020
0.1.0 Nov 2, 2020

#59 in HTTP server


Used in 4 crates

MIT/Apache

67KB
1K SLoC

Actix-storage



Actix storage is a simple wrapper around some key-value storages to provide basic operations without knowing the backend in advance.

Install

Actix-storage is meant to be used alongside one the implementor crates, ex:

# Cargo.toml
[dependencies]
actix-storage = "0.1"
actix-storage-hashmap = "0.1"

Usage

After you picked an implementor:

use actix_storage::{Storage, Format};
use actix_storage_hashmap::HashMapActor;
use actix_web::{App, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
   // Intialize the implementor according to its docs
   let store = HashMapActor::start_default();

   // Give it to the Storage struct
   let storage = Storage::build().expiry_store(store).finish();

   // Or if it doesn't support expiring functionality
   // it will give errors if those methods are called
   let storage = Storage::build().store(store).finish();

   // It is also possible to feed a seprate expiry,
   // as long as it works on the same storage backend
   let storage = Storage::build().expiry(expiry).finish();

   // It is also possible to add a format to directly
   // set and get values using serde.
   let storage = Storage::build().store(expiry).format(Format::Json).finish();


   // Store it with .data
   let server = HttpServer::new(move || {
      App::new()
            .data(storage.clone())
   });
   server.bind("localhost:5000")?.run().await
}

And later in your handlers

async fn index(storage: web::Data<Storage>) -> Result<String, Error>{
   storage.set_bytes("key", "value").await;
   let val = storage.get_bytes("key").await?.unwrap_or_default();

   // Ot if you defined a serde format
   let number: i32 = 5
   storage.set("number", number);
   let x: i32 = storage.get("number");

   Ok(std::str::from_utf8(&val)
      .map_err(|err| error::ErrorInternalServerError("Storage error"))?.to_string())
}

Implementations

actix-storage-hashmap docs.rs docs

actix-storage-dashmap docs.rs docs

actix-storage-sled docs.rs docs

actix-storage-redis docs.rs docs

Why?

It can be usefull when:

  1. You don't know what kind of storage you'll want.
  2. You can't afford the long time compilation of some dbs while developing
    • hashmap store compiles pretty fast
  3. You're writing a general purpose library and you want to let the user decide

Why not?

If you really care about every drop of your application performance then actix-storage may not be for you, as it uses dynamic dispatching internally.

Examples

There are bunch of examples in the examples folder, very basic ones thought, but it will give you the idea.

License

This project is licensed under either of

at your option.

Dependencies

~21MB
~496K SLoC