Skip to content

缓存使用

当前内部缓存包括:内存缓存,Redis缓存,MySql缓存

使用默认缓存

c#
private readonly ICache _cache;

public CacheController(ICache cache)
{
  _cache = cache;
}

[HttpGet("set")]
public void Set()
{
  var person = _cache.Get<string>("123456");
}

使用内存缓存

c#
private readonly ICache<MemoryCache> _memoryCache;

public CacheController(ICache<MemoryCache> memoryCache)
{
  _memoryCache = memoryCache;
}

[HttpGet("set")]
public void Set()
{
  _memoryCache.Get<string>("123456");
}

在多服务器实例(负载)使用时,当缓存修改后,需要清空其他实例的缓存,则使用下面方法:

C#
cache.PublishClearNotify("CacheKey", 0); // 发布清空通知

使用Redis缓存

c#
private readonly ICache<RedisCache> _redisCache;

public CacheController(ICache<RedisCache> redisCache)
{
  _redisCache = redisCache;
}

[HttpGet("set")]
public void Set()
{
  _redisCache.Get<string>("123456");
}

使用MySql缓存

c#
private readonly ICache<MySqlCache> _mySqlCache;

public CacheController(ICache<MySqlCache> mySqlCache)
{
  _mySqlCache = mySqlCache;
}

[HttpGet("set")]
public void Set()
{
  _mySqlCache.Get<string>("123456");
}

使用一级缓存,具体定义在appsettings.json

c#
private readonly ICacheL1 _cacheL1;

public CacheController(ICacheL1 cacheL1)
{
  _cacheL1 = cacheL1;
}

[HttpGet("set")]
public void Set()
{
  _cacheL1.Get<string>("123456");
}

使用二级缓存,具体定义在appsettings.json

c#
private readonly ICacheL2 _cacheL2;

public CacheController(ICacheL2 cacheL2)
{
  _cacheL2 = cacheL2;
}

[HttpGet("set")]
public void Set()
{
  _cacheL2.Get<string>("123456");
}

使用三级缓存,具体定义在appsettings.json

c#
private readonly ICacheL3 _cacheL3;

public CacheController(ICacheL3 cacheL3)
{
  _cacheL3 = cacheL3;
}

[HttpGet("set")]
public void Set()
{
  _cacheL3.Get<string>("123456");
}

默认缓存 和 缓存配置项

js
{
  ......
  "Cache": {
    "Default": "MemoryCache", // 默认缓存
    "Level1": "MemoryCache", // 一级缓存
    "Level2": "RedisCache", // 二级缓存
    "Level3": "MySqlCache", // 三级缓存
    "MemoryCache": {
      "SizeLimit": 100,
      "CompactionPercentage": 0.02,
      "ExpirationScanFrequency": 3
    },
    "RedisCache": {
      "InitalDb": 0,
      "Host": "127.0.0.1",
      "Password": "",
      "PoolTimeOutSeconds": "30",
      "PoolSize": 100
    },
    "MySqlCache": {
      "ValidScanSeconds": 30, // 扫描过期
      "ConnectionString": "server=......" // 连接字符串
    }
  }
  ......
}

广州宝点数字化科技