雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

.NET8使用缓存的几种方法

2024-07-17 33

.NET 8提供了多种方法来使用缓存,从简单的内存缓存到分布式缓存和持久性缓存。下面是.NET 8中使用缓存的几种常见方法:

内存缓存 (Memory Cache):

内存缓存是.NET应用程序中最简单和最快速的缓存方式之一。.NET 8提供了MemoryCache类来实现内存缓存。你可以将数据存储在内存中,并指定过期策略以控制缓存项的生命周期。

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;

public class CacheService
{
    private readonly IMemoryCache _memoryCache;

    public CacheService(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }

    public async Task<string> GetCachedData(string key)
    {
        if (!_memoryCache.TryGetValue(key, out string cachedData))
        {
            // Fetch data from the data source
            cachedData = await FetchDataFromDataSource(key);

            // Store the data in cache
            _memoryCache.Set(key, cachedData, TimeSpan.FromMinutes(10));
        }
        return cachedData;
    }

    private Task<string> FetchDataFromDataSource(string key)
    {
        // Simulated data fetching from a data source
        return Task.FromResult($"Data for {key}");
    }
}

分布式缓存 (Distributed Cache):

对于需要在多个服务器之间共享缓存数据的场景,可以使用分布式缓存。.NET 8提供了IDistributedCache接口,可以使用不同的实现(如Redis、SQL Server等)来实现分布式缓存。

using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed;

public class CacheService
{
    private readonly IDistributedCache _distributedCache;

    public CacheService(IDistributedCache distributedCache)
    {
        _distributedCache = distributedCache;
    }

    public async Task<string> GetCachedData(string key)
    {
        var cachedData = await _distributedCache.GetStringAsync(key);

        if (cachedData == null)
        {
            // Fetch data from the data source
            cachedData = await FetchDataFromDataSource(key);

            // Store the data in cache
            await _distributedCache.SetStringAsync(key, cachedData, new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
            });
        }
        return cachedData;
    }

    private Task<string> FetchDataFromDataSource(string key)
    {
        // Simulated data fetching from a data source
        return Task.FromResult($"Data for {key}");
    }
}

HTTP 缓存:

.NET 8通过HTTP协议提供了缓存支持,你可以利用HTTP标头来控制缓存行为,例如Cache-Control和Expires。通过这种方式,你可以在客户端和服务器之间缓存HTTP响应,减少网络流量和提高性能。

using Microsoft.AspNetCore.Mvc;

public class CacheController : ControllerBase
{
    [HttpGet("/api/data")]
    [ResponseCache(Duration = 60)] // Cache for 60 seconds
    public IActionResult GetData()
    {
        // Fetch and return data
        return Ok("Data");
    }
}

通过使用这些方法,你可以在.NET 8应用程序中有效地利用缓存来提高性能并降低资源消耗。

更新于:2个月前
赞一波!

文章评论

全部评论