MichaCo / CacheManager

CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features.
http://cachemanager.michaco.net
Apache License 2.0
2.34k stars 456 forks source link

Caching certain types in different handles #193

Closed PaulRReynolds closed 6 years ago

PaulRReynolds commented 6 years ago

Hi Michael,

I'm just working on an .Net Core application which will use CacheManager to cache a wide variety of data types, and I'm wondering what the best way is to handle some types differently to others?

Basically, I'm using a 2-level cache (MsMemory and Redis), with Redis Backplane. However, there are certain complex types which I only need to cache in-memory, and don't need to invalidate (they're generated in code and don't change). I want to avoid the serialization/network traffic I'd get pushing this up to Redis.

What's the best approach to take?

Here's my current config for my 2-level cache:

{
  "$schema": "http://cachemanager.michaco.net/schemas/cachemanager.json#",
  "cacheManagers": [
    {
      "maxRetries": 1000,
      "name": "two-level-cache",
      "retryTimeout": 100,
      "updateMode": "Up",
      "backplane": {
        "key": "redisConnection",
        "knownType": "Redis",
        "channelName": "CacheChannel"
      },
      "loggerFactory": {
        "knownType": "Microsoft"
      },
      "serializer": {
        "knownType": "Json"
      },
      "handles": [
        {
          "knownType": "MsMemory",
          "expirationMode": "Absolute",
          "expirationTimeout": "1:0:0",
          "isBackplaneSource": false,
          "name": "memory cache"
        },
        {
          "knownType": "Redis",
          "key": "redisConnection",
          "isBackplaneSource": true
        }
      ]
    }
  ]
}

My Startup.cs looks like this:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddCacheManagerConfiguration(Configuration, cfg =>
    {
        cfg.WithMicrosoftLogging(services);
        cfg.WithRedisConfiguration("redisConnection", cacheOptions.ConnectionString, database: 1);
    });
    services.AddCacheManager();
}
MichaCo commented 6 years ago

You can use a different CacheManager configuration with only one cache handle. For injection, I recently added some overloads to specify a configuration for a specific type.

See samples: https://github.com/MichaCo/CacheManager/blob/dev/samples/AspnetCore.WebApp/Startup.cs#L44

PaulRReynolds commented 6 years ago

Great, thanks! That will work nicely, and it keeps the configuration at startup instead of when I use the cache.