Skip to content

缓存服务

在服务端命令中,有些数据获取需要较大开销,例如通过访问数据库获取数据,或者通过网络请求(WebService)获取数据。频繁的执行这样的操作可能会对服务器性能造成影响,而如果这部分数据实际变化不并不频繁,并且可以接受获取并不实时的数据,可以考虑使用缓存服务来缓存获取到的数据。

活字格服务端命令的上下文参数中的 CacheService 属性可以帮助开发者实现缓存服务。

示例代码:

csharp
public class MyPluginServerCommand : Command, ICommandExecutableInServerSideAsync
{
    public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
    {
        var cacheKey = "cacheKey";
        var cachedValue = dataContext.CacheService.Get(cacheKey);
        if (cachedValue == null)
        {
            cachedValue = "需要被缓存的值,通常,需要缓存的值来自数据库或网络请求";
            dataContext.CacheService.Add(cacheKey, cachedValue, TimeSpan.FromMinutes(10));
        }
        return new ExecuteResult() { Message = cachedValue?.ToString() };
    }
    public override CommandScope GetCommandScope()
    {
        return CommandScope.ExecutableInServer;
    }
}

代码说明:

  1. 通过CacheService.Get,检查制定Key是否有缓存数据。
  2. 第一次请求时,缓存数据为空,则可以真正的通过访问数据库或网络获取数据
  3. 数据获取成功后,把数据通过 CacheService.Add 方法添加到缓存中
    1. 第一个参数时 Key,不同的Key用于区分不同的缓存,建议设计一个可以表达缓存内容且不会与其他缓存冲突的值,例如,请求时获取销售业绩排名前十的员工信息,Key可以为 "Top10_Sales_Cache_Data"
    2. 第二个参数为缓存的内容
    3. 第三个参数为缓存时长,示例代码中指定了缓存 10 分钟。通常应该根据业务数据的过期容忍程度和变化频繁程度来决定这个时间。时间达到时,缓存会被自动清空。再次请求数据时会执行第二步。
  4. 再次请求数据时,走到第一步,由于缓存存在,直接返回缓存中的数据

ICacheService 接口说明

方法说明
bool Exists(string key)判断制定Key的缓存是否存在
bool Add(string key, object value)添加缓存
bool Add(string key, object value, TimeSpan expiresIn)添加缓存,指定缓存过期时间
bool Remove(string key)强制清除缓存
void RemoveAll(IEnumerable<string> keys)一次强制清除多个Key的缓存
T Get<T>(string key)获取缓存
object Get(string key)获取缓存
bool Replace(string key, object value)更新缓存
bool Replace(string key, object value, TimeSpan expiresIn)更新缓存,并制定新的缓存过期时间

在活字格中 ICacheService 默认有两个版本的实现:

  • 默认实现是使用 .net 6 的 MemoryCache实现
  • 如果活字格服务器开启了负载均衡,则缓存数据会保存再 Redis 数据库中

更新: 2022-12-04 21:06:22
原文: https://www.yuque.com/robert-bh51n/ea8l6c/kwqt50861mhhaqnb