Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sj-distributor/FastCache
dotnetcore, dotnet cache, dotnet redis, dotnet InMemoryCache
https://github.com/sj-distributor/FastCache
Last synced: about 2 months ago
JSON representation
dotnetcore, dotnet cache, dotnet redis, dotnet InMemoryCache
- Host: GitHub
- URL: https://github.com/sj-distributor/FastCache
- Owner: sj-distributor
- License: mit
- Created: 2022-05-06T10:09:48.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2024-06-05T08:04:54.000Z (7 months ago)
- Last Synced: 2024-08-27T04:15:15.117Z (4 months ago)
- Language: C#
- Size: 112 KB
- Stars: 43
- Watchers: 6
- Forks: 6
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome - sj-distributor/FastCache - dotnetcore, dotnet cache, dotnet redis, dotnet InMemoryCache (C\#)
README
[![Build Status](https://github.com/sj-distributor/FastCache/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/sj-distributor/FastCache/actions?query=branch%3Amaster)
[![codecov](https://codecov.io/gh/sj-distributor/FastCache/branch/master/graph/badge.svg?token=XV3W873RGV)](https://codecov.io/gh/sj-distributor/FastCache)
[![NuGet version (FastCache.Core)](https://img.shields.io/nuget/v/FastCache.Core.svg?style=flat-square)](https://www.nuget.org/packages/FastCache.Core/)
![](https://img.shields.io/badge/license-MIT-green)## π₯Easily to use cacheπ₯
* InMemory Support
* Integrate into Redis caching
* Fast, concurrent, evicted memory, support big cache## π€ Install
Choose caching provider that you need and install it via Nuget.
```
Install-Package FastCache.InMemory
Install-Package FastCache.Redis
Install-Package FastCache.MultiSource
```## π Quick start
```C#
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());
builder.Services.AddInMemoryCache(); // InMemory// builder.Services.AddMultiBucketsInMemoryCache(); // Big cache
// builder.Services.AddRedisCache("server=localhost:6379;timeout=5000;MaxMessageSize=1024000;Expire=3600", canGetRedisClient: true) // "Expire=3600" is redis global timeout
// canGetRedisClient = true => get redisClient instance
// var redisClient = serviceProvider.GetService();// UserService.cs
[Cacheable("user-single", "{id}", 60 * 30)] // Cache expires after two seconds
public virtual User Single(string id)
{
return _dbContext.Set().Single(x => x.Id == id);
}**********************************
***** Method must be virtual *****
**********************************
```## π Support Autofac
```C#
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer(build =>
{
build.RegisterDynamicProxy();
});
```## βοΈ Use in Controller
```C#
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());
builder.Services.AddInMemoryCache(); // InMemorybuilder.Services.AddMvc().AddControllersAsServices(); // the key point
// UserController.cs
[ApiController]
[Route("/user")]
public class UserController : ControllerBase
{
[Route("/"), HttpGet]
[Cacheable("user-single", "{id}", 60 * 10)]
public virtual User Get(string id)
{
return _userService.Single(id);
}
}
**********************************
***** Method must be "virtual" *****
**********************************
```## β± About Cache expiration ( For InMemory )
* There are three ways of cache eviction, `LRU` and `TTL` and `Random`## πͺ£ About InMemory BigCache ( Multi Buckets )
* Fast. Performance scales on multi-core CPUs.
* The cache consists of many buckets, each with its own lock. This helps scaling the performance on multi-core CPUs,
since multiple CPUs may concurrently access distinct buckets.
* `FastCache.InMemory` automatically evicts old entries when reaching the maximum cache size set on its creation.## π Redis cluster
`builder.Services.AddRedisCache("server=127.0.0.1:6000,127.0.0.1:7000,127.0.0.1:6379;db=3;timeout=7000")`
```
This Redis component supports Redis Cluster, configure any node address,
it will be able to automatically discover other addresses and slot distribution,
and use the correct node when performing read and write operations.This Redis component does not directly support the Redis sentinel, but supports it in the form of active-standby failover.
```## Cache automatic eviction
```C#
// UserService.cs
public class UserService
{
[Cacheable("user-single", "{id}", 2)] // Cache expires after two seconds
public virtual User Single(string id)
{
return _dbContext.Set().Single(x => x.Id == id);
}
}```
## Active cache eviction
```C#
// UserService.cs
public class UserService
{
[Cacheable("user-single", "{id}", 2)] // Cache expires after two seconds
public virtual User Single(string id)
{
return _dbContext.Set().Single(x => x.Id == id);
}
[Evictable(new[] { "user-single", "other cache name" }, "{id}")]
// [Evictable(new[] { "user" }, "{id}*")] // when {id} is "123", it will match keys starting with user:123 and perform a fuzzy deletion.
public virtual void Delete(string id)
{
// delete logic...
}
}```
## π» Match both uses
```C#
// UserService.cs
public class UserService
{
[Cacheable("user-single", "{id}")] // cache never expires
public virtual User Single(string id)
{
// Get User logic...
}
[Cacheable("user-single", "{user:id}")]
[Evictable(new[] { "user-single", "other cache name" }, "{user:id}")]
public virtual User Update(User user)
{
// Update logic...
}
}**********************************************
The Update method will be executed first.
After the method is successfully executed, the setup cache will be invalidated,
and finally the Cacheable operation will be executed.STEP:
1. When "user:id" = "123"
2. Then Evict cache: "user-single:123"
3. Then After updated will caching: "user-single:123" -> { latest user data }π This means that the cache will always be kept up to date,
thus triggering queries to the database will be significantly reduced π**********************************************
```## πΊ Multi Source ( Currently supports Redis and inMemory )
```C#
// Program.cs
builder.Services.AddMultiSourceCache(
"server=localhost:6379;timeout=5000;MaxMessageSize=1024000;Expire=3600", // redis connectionString
true // can get redis client
);// UserController.cs
// Target.Redis Target.InMemory
[HttpGet]
[MultiSourceCacheable("MultiSource-single", "{id}", Target.Redis, 60)] // Target.Redis
public virtual async Task Get1(string id)
{
return await _userService.Single(id).Result;
}[HttpGet]
[MultiSourceCacheable("MultiSource-single", "{id}", Target.InMemory, 60)] // Target.InMemory
public virtual async Task Get2(string id)
{
return await _userService.Single(id).Result;
}**********************************************
According to business needs, flexibly store the cache in redis or memory
**********************************************
```## π Parameter Description
```c#
// MemoryCache
public static void AddInMemoryCache(
this IServiceCollection services,
int maxCapacity = 1000000,
MaxMemoryPolicy maxMemoryPolicy = MaxMemoryPolicy.LRU, int cleanUpPercentage = 10
)
{ // ... }// MulitBucketsMemoryCache
public static void AddMultiBucketsInMemoryCache(
this IServiceCollection services,
uint buckets = 5,
uint maxCapacity = 500000,
MaxMemoryPolicy maxMemoryPolicy = MaxMemoryPolicy.LRU,
int cleanUpPercentage = 10)
{ //... }
```| Parameter | Type | Default | Require | Explain |
|:------------------------------------------------------------:|:----:|:-------------------:|:-------:|---------------------------------------------------------------------------------------------------------------------------------------------|
| `buckets` | uint | 5 | false | The number of containers to store the cache, up to 128 |
| `bucketMaxCapacity` | uint | 1000000 | false | (MemoryCache) Initialize capacity
(MulitBucketsMemroyCache) The capacity of each barrel, it is recommended that 500,000 ~ 1,000,000 |
| `maxMemoryPolicy` | MaxMemoryPolicy | MaxMemoryPolicy.LRU | false | LRU = Least Recently Used , TTL = Time To Live, Or RANDOM |
| `cleanUpPercentage` | int | 10 | false | After the capacity is removed, the percentage deleted |## Variable explanation
```
// foo:bar:1 -> "item1"
{
"foo": {
"bar": [
"item1",
"qux"
]
}
}// foo:bar:0:url -> "test.weather.com"
{
"foo": {
"bar": [
{
"url": "test.weather.com",
"key": "DEV1234567"
}
]
}
}
```