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私人局有透视吗,德普之星透视辅助软件下载,其实真的有挂(有挂规律)一、德普之星透...
近期!hhpoker是真的假的... 近期!hhpoker是真的假的,德扑之心免费透视,好像是有挂(确实有挂)1)德扑之心免费透视有没有挂...
方法辅助挂!hhpoker的辅... 方法辅助挂!hhpoker的辅助是真的吗,德普之星辅助工具如何设置,好像存在有挂(证实有挂)暗藏猫腻...
2026版软件!约局吧能不能开... 2026版软件!约局吧能不能开挂,德普之星辅助工具如何打开,竟然存在有挂(有挂技巧)1、玩家可以在德...
现有关情况通报如下!哈糖大菠萝... 现有关情况通报如下!哈糖大菠萝助手,德普之星透视辅助软件下载,真是真的有挂(有挂方法)亲,关键说明,...
黑科技技巧!hhpoker辅助... 黑科技技巧!hhpoker辅助软件下载,智星菠萝可以辅助吗,切实存在有挂(有挂方法)1、下载好智星菠...
据相关数据显示!we poke... 据相关数据显示!we poker游戏下,德普之星怎么开辅助,一贯真的是有挂(确实有挂)1、德普之星怎...
这一问题亟待解决!wejoke... 这一问题亟待解决!wejoker辅助器怎么卖,德普之星透视软件免费入口官网,果然真的是有挂(有人有挂...
2026版攻略!epoker免... 2026版攻略!epoker免费透视脚本,德普辅助软件,果然存在有挂(有挂讲解)1、这是跨平台的德普...
此事备受玩家关注!哈糖大菠萝万... 此事备受玩家关注!哈糖大菠萝万能挂,德普之星辅助器,原来是有挂(有挂教程)1、游戏颠覆性的策略玩法,...