94 lines
2.8 KiB
C#
94 lines
2.8 KiB
C#
using Microsoft.Extensions.Options;
|
|
using Newtonsoft.Json;
|
|
using StackExchange.Redis;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using WMS.Web.Domain.Options;
|
|
|
|
namespace WMS.Web.Domain.Services.Public
|
|
{
|
|
public class RedisClientService
|
|
{
|
|
private static readonly object Locker = new object();
|
|
|
|
private ConnectionMultiplexer redisMultiplexer;
|
|
IDatabase db = null;
|
|
private readonly AppOptions _options;
|
|
public RedisClientService(IOptions<AppOptions> options)
|
|
{
|
|
_options = options?.Value;
|
|
redisMultiplexer = ConnectionMultiplexer.Connect(_options.RedisConnectionString);
|
|
db = redisMultiplexer.GetDatabase();
|
|
}
|
|
|
|
#region String
|
|
/// <summary>
|
|
/// 保存单个key value
|
|
/// </summary>
|
|
/// <param name="key"></param>
|
|
/// <param name="value"></param>
|
|
/// <param name="expiry"></param>
|
|
/// <returns></returns>
|
|
public bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?))
|
|
{
|
|
var lastKey = _options.RedisDirectory + ":" + key;
|
|
return db.StringSet(lastKey, value, expiry);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取单个key的值
|
|
/// </summary>
|
|
public RedisValue GetStringKey(string key)
|
|
{
|
|
var lastKey = _options.RedisDirectory + ":" + key;
|
|
return db.StringGet(lastKey);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 移除redis
|
|
/// </summary>
|
|
/// <param name="key"></param>
|
|
/// <returns></returns>
|
|
public bool RemoveStringKey(string key)
|
|
{
|
|
var lastKey = _options.RedisDirectory + ":" + key;
|
|
return db.KeyDelete(lastKey);
|
|
}
|
|
/// <summary>
|
|
/// 获取一个key的对象
|
|
/// </summary>
|
|
public T GetStringKey<T>(string key)
|
|
{
|
|
if (db == null)
|
|
{
|
|
return default;
|
|
}
|
|
var lastKey = _options.RedisDirectory + ":" + key;
|
|
var value = db.StringGet(lastKey);
|
|
if (value.IsNullOrEmpty)
|
|
{
|
|
return default;
|
|
}
|
|
return JsonConvert.DeserializeObject<T>(value);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 保存一个对象
|
|
/// </summary>
|
|
/// <param name="obj"></param>
|
|
public bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
|
|
{
|
|
if (db == null)
|
|
{
|
|
return false;
|
|
}
|
|
var lastKey = _options.RedisDirectory + ":" + key;
|
|
string json = JsonConvert.SerializeObject(obj);
|
|
return db.StringSet(lastKey, json, expiry);
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|