Redis不会从数据库中删除记录

问题描述 投票:1回答:2

首先,我正在使用此包装器:https://github.com/garywoodfine/redis-mvc-core/blob/master/RedisConfiguration/RedisVoteService.csDelete(...)似乎不起作用。我想我尝试过IDistributedCache,它过去也没有删除对象,但它至少使所有属性都为空。

您可以在我尝试过的FlushDatabase()注释中看到它,但似乎也没有用。我想要Delete方法删除对象。不仅将它们为空(这也不起作用)。

有什么想法吗?老实说,我想得到一个支持List<T>的更好的包装器。

enter image description here

var redis = new RedisAlgorithmService<BotSession>(_connectionFactory);
var test = redis.Get("Test");
if (test == null)
    redis.Save("Test", new BotSession(TrendType.Uptrend, bot.Id));
test.NTimes = 123;
redis.Delete("Test");
using StackExchange.Redis;
using System;

namespace Binance.Redis
{
    public class RedisAlgorithmService<T> : BaseService<T>, IRedisService<T>
    {
        internal readonly IRedisConnectionFactory _connectionFactory;
        protected readonly IDatabase _database;

        public RedisAlgorithmService(IRedisConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
            _database = _connectionFactory.Connection().GetDatabase();
        }

        public void Delete(string key)
        {
            if (string.IsNullOrWhiteSpace(key) || key.Contains(":")) 
                throw new ArgumentException("Invalid key!");

            key = GenerateKey(key);
            _database.KeyDelete(key);

            // _database.HashDelete(key, );

            // var endpoints = _connectionFactory.Connection().GetEndPoints();
            // _connectionFactory.Connection().GetServer(endpoints[0]).FlushDatabase();
        }

        public T Get(string key)
        {
            key = GenerateKey(key);
            var hash = _database.HashGetAll(key);
            return MapFromHash(hash);
        }

        public void Save(string key, T obj)
        {
            if (obj != null)
            {
                var hash = GenerateHash(obj);
                key = GenerateKey(key);

                if (_database.HashLength(key) == 0)
                {
                    _database.HashSet(key, hash);
                }
                else
                {
                    var props = Properties;
                    foreach (var item in props)
                    {
                        if (_database.HashExists(key, item.Name))
                        {
                            _database.HashIncrement(key, item.Name, Convert.ToInt32(item.GetValue(obj)));
                        }
                    }
                }

            }
        }
    }
}

asp.net-core redis
2个回答
1
投票

不确定FlushDatabase()FlushAllDatabase()是否正是您想要的:

  • FLUSHDB –从连接的当前数据库中删除所有密钥。
  • FLUSHALL –从所有数据库中删除所有键。

还有另一种使用扩展方法并将Newtonsoft.Json用作序列化器/解串器的解决方法。我知道IDistributedCache仅支持字符串/字节数组作为输入,并且您不能将类对象传递给它,这种解决方法将帮助您做到这一点。

Startup.cs

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost";
    options.InstanceName = "name";
});

CacheExtensions.cs

namespace TestProject.Extensions
{
    public static class CacheExtensions
    {
        public static async Task<T> SetAsync<T>(this IDistributedCache cache, string key, T item)
        {
            var json = JsonConvert.SerializeObject(item);

            await cache.SetStringAsync(key, json);

            return await cache.GetAsync<T>(key);
        }

        public static async Task<T> SetAsync<T>(this IDistributedCache cache, string key, T item, int expirationInHours)
        {
            var json = JsonConvert.SerializeObject(item);

            await cache.SetStringAsync(key, json, new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(expirationInHours)
            });

            return await cache.GetAsync<T>(key);
        }

        public static async Task<T> GetAsync<T>(this IDistributedCache cache, string key)
        {
            var json = await cache.GetStringAsync(key);

            if (json == null)
                return default;

            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}

DI IDistributedCache

private readonly IDistributedCache _cache;

public TestService(IDistributedCache cache)
{
    _cache = cache;
}

并像这样使用它:

List<Test> testList = new List<Test>
{
    new Test(...),
    new Test(...)
};

var test = await _cache.GetAsync<List<Test>>("ListKey");
await _cache.SetAsync("ListKey", testList);
await _cache.RemoveAsync("ListKey");

var test2 = await _cache.GetAsync<Test>("key");
await _cache.SetAsync("key", new Test(...));
await _cache.RemoveAsync("key");

希望有帮助。


0
投票

我不确定这是否对您有帮助。我可以看到您尝试过的此方法,但似乎不完整。

© www.soinside.com 2019 - 2024. All rights reserved.