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 options) { _options = options?.Value; redisMultiplexer = ConnectionMultiplexer.Connect(_options.RedisConnectionString); db = redisMultiplexer.GetDatabase(); } #region String /// /// 保存单个key value /// /// /// /// /// public bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?)) { var lastKey = _options.RedisDirectory + ":" + key; return db.StringSet(lastKey, value, expiry); } /// /// 获取单个key的值 /// public RedisValue GetStringKey(string key) { var lastKey = _options.RedisDirectory + ":" + key; return db.StringGet(lastKey); } /// /// 移除redis /// /// /// public bool RemoveStringKey(string key) { var lastKey = _options.RedisDirectory + ":" + key; return db.KeyDelete(lastKey); } /// /// 获取一个key的对象 /// public T GetStringKey(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(value); } /// /// 保存一个对象 /// /// public bool SetStringKey(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 } }