using FreeRedis; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WMS.BZServices { public interface IRedisService { int DistributeLock(string lockKey, int timeoutSeconds = 30, bool autoDelay = false); string Get(string key = "key"); T Get(string key = "key"); long Publish(string channel, string message); bool Set(string key, string value, TimeSpan timeSpan); bool Set(string key, T value, TimeSpan timeSpan); void Del(string key); } public class RedisService : IRedisService { private readonly RedisClient _redisClient; private static int _tempInt = 0; /// /// /// /// /// public RedisService( string redisconnect) { _redisClient = new RedisClient(redisconnect); _redisClient.Serialize = obj => JsonConvert.SerializeObject(obj); ;// JsonConvert.SerializeObject(obj); _redisClient.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);// JsonConvert.DeserializeObject(json, type); } /// /// Redis插入 /// /// /// /// /// public bool Set(string key, string value, TimeSpan timeSpan) { _redisClient.Set(key, value, timeSpan); return true; } public bool Set(string key, T value, TimeSpan timeSpan) { _redisClient.Set(key, value, timeSpan); return true; } /// /// 通过key或者Redis值 /// /// /// public string Get(string key) { //可随时改用原生对象操作redis var value = _redisClient.Get(key); return value; } public T Get(string key) { //可随时改用原生对象操作redis var value = _redisClient.Get(key); return value; } public void Del(string key) { _redisClient.Del(key); } /// /// 消息发布 /// /// /// /// public long Publish(string channel, string message) { var value = _redisClient.Publish(channel, message); return value; } /// /// 分布式锁 /// /// 指定锁的key /// 超时秒数,超过时间自动释放锁 /// 是否需要自动延时,true:自动延长过期时间false:不延长过期时间,以设置的过期时间为准 /// public int DistributeLock(string lockKey, int timeoutSeconds = 30, bool autoDelay = false) { //通过别名为1的redis库进行分布式锁 using (_redisClient.Lock(lockKey, timeoutSeconds, autoDelay)) { //被锁住的逻辑 return _tempInt; } } } }