content/integrate/fusioncache/_index.md
FusionCache can transparently handle multiple cache levels by mixing a memory cache and a distributed cache together, getting the best of both worlds. It allows for a sophisticated yet incredibly easy to use developer experience by handling all the complexities of a modern, fast and robust hybrid cache that can deal with the most complex and demanding scenarios. When coupled with Redis, performance, robustness and scaling will not be a problem anymore.
Using the dotnet CLI, run:
dotnet add package ZiggyCreatures.FusionCache
Other packages are also available to work with different distributed caches, serializers, backplanes and more. See the FusionCache docs for more information.
First, install the packages for Redis (with JSON serialization):
dotnet add package ZiggyCreatures.FusionCache
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
dotnet add package ZiggyCreatures.FusionCache.Serialization.SystemTextJson
dotnet add package ZiggyCreatures.FusionCache.Backplane.StackExchangeRedis
Then at startup:
services.AddFusionCache()
.WithSerializer(
new FusionCacheSystemTextJsonSerializer()
)
.WithDistributedCache(
new RedisCache(new RedisCacheOptions { Configuration = "localhost:6379" })
)
.WithBackplane(
new RedisBackplane(new RedisBackplaneOptions { Configuration = "localhost:6379" })
);
Use code like the following to share the Redis connection multiplexer:
var muxer = ConnectionMultiplexer.Connect("localhost:6379")
services.AddFusionCache()
.WithSerializer(
new FusionCacheSystemTextJsonSerializer()
)
.WithDistributedCache(
new RedisCache(new RedisCacheOptions { ConnectionMultiplexerFactory = () => muxer })
)
.WithBackplane(
new RedisBackplane(new RedisBackplaneOptions { ConnectionMultiplexerFactory = () => muxer })
);
FusionCache is now ready to use. The simple example below demonstrates the GetOrSetAsync method but see Core Methods in the FusionCache docs for full details of the API.
var product1 = await cache.GetOrSetAsync<Product>(
"product:1",
async _ => GetProductFromDb(1),
tags: ["sales", "product"]
);
var product2 = await cache.GetOrSetAsync<Product>(
"product:2",
async _ => GetProductFromDb(2),
tags: ["sales", "product"]
);
var order = await cache.GetOrSetAsync<Order>(
"order:42",
async _ => GetOrderFromDb(42),
tags: ["sales", "order"]
);
// LATER...
await cache.RemoveByTagAsync("product");
// NOW BOTH product:1 AND product:2 ARE GONE, ONLY order:42 IS STILL IN THE CACHE
To learn more about FusionCache and its advanced features: