redis ASP.NET Core -错误CS 1929 IMemoryCache不包含“GetString”的定义和最佳扩展方法重载

axr492tv  于 2023-05-05  发布在  Redis
关注(0)|答案(1)|浏览(190)

我正在ASP.NET Core-6中实现Redis的内存缓存,使用:

Microsoft.Extensions.Caching.StackExchangeRedis

我有这个代码:

public class CacheService : ICacheService
{
    private readonly IMemoryCache _cache;

    public CacheService(IMemoryCache cache)
    {
        _cache = cache;
    }

    public T Get<T>(string key)
    {
        var value = _cache.GetString(key);

        if (value != null)
        {
            return JsonConvert.DeserializeObject<T>(value);
        }

        return default;
    }

    public T Set<T>(string key, T value)
    {
        _cache.SetString(key, JsonConvert.SerializeObject(value), new MemoryCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(20),
            SlidingExpiration = TimeSpan.FromMinutes(30)
        });
        return value;
    }
}

但我犯了这些错误:

Error   CS1929  'IMemoryCache' does not contain a definition for 'GetString' and the best extension method overload 'EncodingExtensions.GetString(Encoding, in ReadOnlySequence<byte>)' requires a receiver of type 'System.Text.Encoding'

和/或

Error   CS1061  'IMemoryCache' does not contain a definition for 'SetString' and no accessible extension method 'SetString' accepting a first argument of type 'IMemoryCache' could be found (are you missing a using directive or an assembly reference?)

然后:
_memoryCache.GetString(key)和_memoryCache.SetString突出显示。
我该如何纠正这些错误?

e4yzc0pl

e4yzc0pl1#

IMemoryCache没有GetString方法,但IDistributedCache有一个。如果你想用于开发/测试目的,你可以使用框架提供的分布式内存缓存实现注册IDistributedCache

builder.Services.AddDistributedMemoryCache();

但请注意:
分布式内存缓存不是一个真正的分布式缓存。缓存项由运行应用的服务器上的应用示例存储。
还要注意的是,RedisCache没有实现IMemoryCache,它是implements IDistributedCache
对于IMemoryCache缓存,不需要显式序列化T,可以使用通用的GetSet方法。只是让你开始:

public class CacheService 
{
    // ...

    public T Get<T>(string key)
    {
        return _cache.Get<T>(key);
    }

    public T Set<T>(string key, T value)
    {
        _cache.Set(key, value, new MemoryCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(20),
            SlidingExpiration = TimeSpan.FromMinutes(30)
        });
        return value;
    }
}

相关问题