Coder Social home page Coder Social logo

strogo / actix-cache Goto Github PK

View Code? Open in Web Editor NEW

This project forked from rambler-digital-solutions/actix-cache

0.0 2.0 0.0 166 KB

Actix cache is a proxy actor and infrastructure for asynchronous and clear cache interaction for Actix actor and Actix-web frameworks.

License: MIT License

Rust 100.00%

actix-cache's Introduction

actix-cache

Build Status Coverage Status

Actix cache is a proxy actor and infrastructure for asynchronous and clear cache interaction for Actix actor and Actix-web frameworks.

Features

  • Async/Sync cache backend support.
  • Dogpile effect prevention.
  • Stale cache mechanics.
  • Automatic cache key generation.
  • Detailed Prometheus metrics out of the box.

Backend implementations

At this time supported or planned next cache backend implementation:

  • Redis backend (actix-cache-redis)
  • In-memory backend

Feature flags

  • redis - Enabled by default. Add support for redis backend.
  • derive - Support for Cacheable trait derive macros.
  • metrics - Support for Prometheus metrics.

Example

Dependencies:

[dependencies]
actix-cache = "0.2"

Code:

First of all, you should derive Cacheable trait for your actix Message:

NOTE: Default cache key implementation based on serde_qs crate and have some restrictions.

use actix::prelude::*;
use actix_cache::Cacheable; // With features=["derive"]
use actix_derive::Message;
use serde::{Deserialize, Serialize};
struct Pong;

#[derive(Message, Cacheable, Serialize)]
#[rtype(result = "Result<Pong, ()>")]
struct Ping {
    id: i32,
}

Or implement that trait manually:

use actix_cache::{Cacheable, CacheError};

struct Ping { id: i32 }

impl Cacheable for Ping {
    fn cache_message_key(&self) -> Result<String, CacheError> {
        Ok(format!("{}::{}", self.cache_key_prefix(), self.id))
    }
    fn cache_key_prefix(&self) -> String { "Ping".to_owned() }
}

Next step is to instantiate CacheActor with default backend:

use actix::prelude::*;
use actix_cache::{CacheError, Cache};

#[actix_rt::main]
async fn main() -> Result<(), CacheError> {
    let cache = Cache::new()
        .await?
        .start();
   Ok(())
}

And the last step is using cache in your code (actix-web handler for example). This full example and other examples you can see on github.com

use actix::prelude::*;
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use actix_cache::{Cache, Cacheable};
use serde::Serialize;

struct FibonacciActor;

impl Actor for FibonacciActor { type Context = Context<Self>; }

#[derive(Message, Cacheable, Serialize)]
#[rtype(result = "u64")]
struct GetNumber {
    number: u8
}

impl Handler<GetNumber> for FibonacciActor {
    type Result = <GetNumber as Message>::Result;

    fn handle(&mut self, msg: GetNumber, _ctx: &mut Self::Context) -> Self::Result {
        42
    }
}

async fn index(
    fib: web::Data<Addr<FibonacciActor>>,
    cache: web::Data<Addr<Cache>>
) -> impl Responder {
    let query = GetNumber { number: 40 };
    let number = cache
        .send(query.into_cache(&fib))
        .await
        .unwrap()
        .unwrap();
    HttpResponse::Ok().body(format!("Generate Fibonacci number {}", number))
}

actix-cache's People

Contributors

andreyermilov avatar singulared avatar zhiburt avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.