EasyCaching Documentation

repository·dev·Indexed 24 days ago

https://github.com/dotnetcore/easycaching

An open-source caching library for .NET that provides a unified interface for multiple caching providers, including InMemory, Redis, Memcached, SQLite, and FasterKv. It supports modular provider installation, multiple provider management via IEasyCachingProviderFactory, and caching interception using AspectCore or Castle to separate business logic from caching via attributes.

Tokens
23.3K
Snippets
68
Records
87
Agent score
85%

What's inside EasyCaching

  1. Explore EasyCaching extension libraries

    dev

    EasyCaching can be extended with additional packages to provide specialized functionality. Two notable extensions are:

    • EasyCaching.Extensions.EasyCompressor: Used to compress cache objects. This helps speed up data transfer over networks, reduces bandwidth usage, and lowers the memory footprint of the cache server.
    • EasyCaching.Extensions: Provides integrations for other common .NET libraries and abstractions such as CAP, WebApiClient, and IDistributedCache.
  2. What is HybridCachingProvider and how does it work?

    dev

    The HybridCachingProvider combines local caching (e.g., In-Memory) and distributed caching (e.g., Redis) into a single unified provider.

    Its primary purpose is to ensure that local caches across different application instances stay synchronized. When a cached value is modified in one instance, the provider sends a message via an EasyCaching Bus to notify other application instances to remove their stale local cached values. This prevents different nodes in a distributed system from serving inconsistent data.

  3. How EasyCachingProviderFactory works

    dev

    The EasyCachingProviderFactory allows you to manage multiple independent instances of the same caching type (e.g., multiple different Redis clusters or multiple In-Memory caches) within a single application. This is useful when different business modules require separate caching instances rather than a single shared cache or a hybrid cache.

    It functions similarly to HttpClientFactory, where you register named instances during startup and retrieve them by name using the factory. The factory can create two types of providers:

    1. IEasyCachingProvider
    2. IRedisCachingProvider
  4. Available serialization options in EasyCaching

    dev

    EasyCaching serializes cached content into byte[] for distributed caching. It supports five different serialization providers:

    • Newtonsoft.Json
    • MessagePack
    • System.Text.Json
    • MemoryPack
    • Protobuf

    Note: BinaryFormatter was removed in version v1.7.0 due to lack of support in .NET 5 and later.

  5. Implement Caching Interception with AspectCore

    dev

    Use EasyCaching.Interceptor.AspectCore to separate business logic from caching logic using attributes on your service interfaces. This allows you to declaratively define caching behaviors like retrieval, storage, and eviction without polluting your implementation code.

    Core Attributes

    • [EasyCachingAble(Expiration = X)]: Enables caching for a method with a specific expiration time.
    • [EasyCachingPut(CacheKeyPrefix = "...")]: Caches the result of a method call using a specified key prefix.
    • [EasyCachingEvict(IsBefore = true)]: Evicts (deletes) items from the cache when the method is called.
    public interface IDemoService
    {
        [EasyCachingAble(Expiration = 10)]
        string GetCurrentUtcTime();
    
        [EasyCachingPut(CacheKeyPrefix = "AspectCore")]
        string PutSomething(string str);
    
        [EasyCachingEvict(IsBefore = true)]
        void DeleteSomething(int id);
    }
  6. Understand EasyCaching interception strategies

    dev

    EasyCaching uses Aspect-Oriented Programming (AOP) to automate cache management, replacing manual if-else cache checks with three primary interception strategies that map to CRUD operations:

    • Able: Corresponds to Create and Read. It checks the cache first; if the data is missing, it executes the method and then writes the result to the cache. Best for query operations. Use with caution for high real-time requirement scenarios.
    • Put: Corresponds to Update. It updates the cached data when the intercepted method is called. Use sparingly if the data is updated very frequently.
    • Evict: Corresponds to Delete. It removes the corresponding cached data when the intercepted method is called.

    To use these, you apply specific attributes to your interface or class methods.

  7. Use different serialization methods for different providers

    dev
    Since version 0.6.0, EasyCaching supports named serialization selection. This allows you to configure multiple different Provider instances, each using a different serialization method. This is essential when your architecture requires different serialization strategies for different cache providers (e.g., one provider using MessagePack for performance and another using Newtonsoft.Json for compatibility).
  8. Configure Deep Cloning for Data Integrity

    dev

    When using in-memory caching, if you intend to modify objects after retrieving them from the cache, you must enable Deep Cloning.

    If EnableReadDeepClone is set to false (the default for writes), modifying a retrieved object will directly modify the instance stored in the cache.

    Note: Deep cloning incurs a performance penalty. Only enable it if you need to ensure the cached data remains immutable to consumer modifications.

  9. Configure Interceptor implementations

    dev

    EasyCaching supports two different underlying implementations for its interception logic:

    1. AspectCore-based implementation.
    2. Castle + Autofac.Extras.DynamicProxy-based implementation.

    You can specify a global CacheProviderName in your configuration, but this can be overridden by specifying a specific CacheProviderName directly on the interception attribute.

  10. How the Cache Factory handles multiple providers

    dev
    The Cache Factory is designed to manage scenarios where a project requires multiple cache instances or different types of providers simultaneously. This includes using multiple different providers (e.g., combining InMemory with CSRedis) or multiple instances of the same provider type (e.g., three InMemory instances and two CSRedis instances).
  11. Understand BinaryFormatter serialization in EasyCaching

    dev

    In EasyCaching, BinaryFormatter is the default serializer used when working with EasyCaching.Redis.

    However, it is important to note that EasyCaching.Memcached does not use BinaryFormatter as its default serializer. Instead, EasyCaching.Memcached (via EnyimMemcachedCore) uses Bson as its default, though it does provide a BinaryFormatterTranscoder implementation based on BinaryFormatter.

    ⚠️ Critical Compatibility Warning: BinaryFormatter was removed from EasyCaching starting with version v1.7.0 because it is no longer supported in .NET 5 and later versions due to security and compatibility reasons.

  12. Configure EasyCaching.InMemory via C# code

    dev

    You can configure the in-memory provider in your Startup class using AddEasyCaching. You can use a simple setup or a detailed configuration using InMemoryCachingOptions.

    Simple Configuration

    Use options.UseInMemory("name") to quickly enable a default memory cache.

    Detailed Configuration

    Use options.UseInMemory(config => { ... }, "name") to customize settings like size limits, expiration frequency, and deep cloning behavior.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddEasyCaching(options =>
        {
            // Simple way
            options.UseInMemory("default");
            
            // Detailed way
            options.UseInMemory(config => 
            {
                config.DBConfig = new InMemoryCachingOptions
                {
                    ExpirationScanFrequency = 60, 
                    SizeLimit = 100,       
                    EnableReadDeepClone = true,
                    EnableWriteDeepClone = false,
                };
                config.MaxRdSecond = 120;
                config.EnableLogging = false;
                config.LockMs = 5000;
                config.SleepMs = 300;
            }, "default1");
        });
    }