Files
tnb.server/common/Tnb.Common/Redis/StackExRedisHelper.cs
2024-06-07 17:30:47 +08:00

93 lines
2.6 KiB
C#

using JNPF;
using JNPF.DependencyInjection;
using Newtonsoft.Json;
using Spire.Xls.Core;
using StackExchange.Redis;
using System;
using System.Threading.Tasks;
namespace Tnb.Common.Redis
{
public class StackExRedisHelper : ISingleton
{
private ConnectionMultiplexer _redis;
private IDatabase _db;
// 初始化 Redis 连接
public StackExRedisHelper()
{
RedisOptions _RedisOptions = App.GetConfig<RedisOptions>("Redis", true);
_redis = ConnectionMultiplexer.Connect($"{_RedisOptions.ip}:{_RedisOptions.port},password={_RedisOptions.password}");
_db = _redis.GetDatabase();
}
// 存储字符串值
public void SetString(string key, string value)
{
_db.StringSet(key, value);
}
// 获取字符串值
public string GetString(string key)
{
return _db.StringGet(key);
}
// 存储哈希值
public void SetHash(string key, string field, string value)
{
_db.HashSet(key, field, value);
}
// 获取哈希值
public async Task<string> GetHash(string key, string field)
{
return await _db.HashGetAsync(key, field);
}
public async Task<bool> HashExists(string key, string field)
{
return await _db.HashExistsAsync(key, field);
}
// 存储列表值
public void ListRightPush(string key, string value)
{
_db.ListRightPush(key, value);
}
// 关闭 Redis 连接
public void Close()
{
if (_redis != null && _redis.IsConnected)
{
_redis.Close();
}
}
public async Task<T> TryGetValueByKeyField<T>(string key, string field)
{
if (_db.HashExists(key, field))
{
string data = await GetHash(key, field);
Dictionary<String, String> json = JsonConvert.DeserializeObject<Dictionary<String, String>>(data);
Type type = typeof(T);
if ((!type.IsValueType && type.GetGenericArguments().Length > 0) || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
return (T)Convert.ChangeType(json["Value"], type.GetGenericArguments()[0]);
}
else
{
return (T)Convert.ChangeType(json["Value"], type);
}
// return ;
}
return default(T);
}
}
}