BlazorWASMServerCaching
创始人
2024-12-21 21:00:22
0

Blazor WASM Server可以采用内存缓存或分布式缓存来实现缓存控制。下面是实现内存缓存的代码示例:

使用单例模式创建CacheService类:

public class CacheService
{
    private readonly MemoryCache _cache;

    public CacheService()
    {
        _cache = new MemoryCache(new MemoryCacheOptions());
    }

    public T Get(string cacheKey)
    {
        if (_cache.TryGetValue(cacheKey, out T cacheValue))
        {
            return cacheValue;
        }

        return default;
    }

    public void Set(string cacheKey, T cacheValue, TimeSpan cacheDuration)
    {
        var options = new MemoryCacheEntryOptions()
            .SetSlidingExpiration(cacheDuration);

        _cache.Set(cacheKey, cacheValue, options);
    }

    public void Remove(string cacheKey)
    {
        _cache.Remove(cacheKey);
    }
}

然后在startup.cs文件里将服务注册到DI容器:

services.AddSingleton(typeof(CacheService));

在需要缓存的地方使用:

private readonly CacheService _cacheService;

public MyClass(CacheService cacheService)
{
    _cacheService = cacheService;
}

public async Task GetDataAsync(int id)
{
    var cacheKey = $"MyObject-{id}";
    var cachedData = _cacheService.Get(cacheKey);

    if (cachedData != null)
    {
        return cachedData;
    }

    var data = await GetDataFromServerAsync(id);
    _cacheService.Set(cacheKey, data, TimeSpan.FromMinutes(30));

    return data;
}

这个代码示例中,MyClass类从服务端获取MyObject对象,使用CacheService类实现内存缓存,缓存时间为30分钟。如果缓存已存在,则从缓存中返回数据,否则从服务端获取数据并将其缓存起来。

相关内容

热门资讯

三分钟了解!wepoker俱乐... 三分钟了解!wepoker俱乐部辅助,广西老友玩有破解视频,教你教程(有人有挂)-哔哩哔哩亲,关键说...
关于!wpk透视挂,德普软件,... 关于!wpk透视挂,德普软件,透视教程(有人有挂)-哔哩哔哩1、首先打开德普软件最新版本,在德普软件...
一分钟了解!wepoker轻量... 一分钟了解!wepoker轻量版透视方法,手游字牌辅助脚本工具,新2025教程(有挂讲解)-哔哩哔哩...
热门推荐!拱趴大菠萝可以开挂,... 热门推荐!拱趴大菠萝可以开挂,九九联盟解码器,规律教程(有挂详细)-哔哩哔哩拱趴大菠萝可以开挂辅助器...
玩家必备教程!wepoker可... 玩家必备教程!wepoker可以看底牌,丫丫衡阳字牌2辅助,2025新版教程(讲解有挂)-哔哩哔哩1...
我来教大家!hhpoker德州... 我来教大家!hhpoker德州透视挂,花舍辅助,揭秘攻略(有挂神器)-哔哩哔哩hhpoker德州透视...
分享开挂内幕!pokemmo辅... 分享开挂内幕!pokemmo辅助工具,广西老友玩老师输可以版,透牌教程(有挂透视)-哔哩哔哩1、很好...
攻略讲解!we poker插件... 攻略讲解!we poker插件,wejoker手机版透视脚本,2025新版技巧(有挂方略)-哔哩哔哩...
让我来分享经验!德州之星扫描器... 让我来分享经验!德州之星扫描器,阿拉游戏中心辅助挂教程,曝光教程(有挂辅助)-哔哩哔哩1、阿拉游戏中...
总算了解!德普辅助软件,微乐贵... 总算了解!德普辅助软件,微乐贵阳捉鸡麻将能不能开挂,德州教程(有挂方针)-哔哩哔哩微乐贵阳捉鸡麻将能...