栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Redis使用说明

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Redis使用说明

1.添加引用StackExchange.Redis.dll
2.Redis初始化放在ASP.NET应用程序文件Global.asax.cs的Application_Start中
3.使用举例
public List GetDepartments()
{
var user = this.GetUserInfo();
var key = “deptment:ALL”;
var cache = RedisHelper.Get(key);
if (cache != null)
{
return cache;
}
var depts = c6set.AsQueryable().Where(p => p.ZHR900104 != null).Select(p => new DepartmentPatialModel
{
Code = p.ZHR900104,
PCode = p.SZHR900104,
Name = p.STEXT
}).ToList();
RedisHelper.Set(key, depts, DateTime.Now.AddHours(2));
return depts;
}

using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Casetek.DCS.Common
{
    /// 
    /// RedisHelper帮助类
    /// 
    public class RedisHelper
    {
        private static int initTimes = 3;//初始化次数
        private static int timeOut = 60;//默认超时时间(单位秒)
        private static string configUrl = null;
        private static ConnectionMultiplexer connectionMultiplexer = null;
        private static IServer server = null;
        private static IDatabase database = null;

        /// 
        /// 初始化
        /// 
        public static void Init()
        {
            try
            {
                if (initTimes > 0)
                {
                    --initTimes;
                    configUrl = CommonConstValue.RedisIPAndPassword;
                    if (!CommonConstValue.IsNormalDevelopmentEnvironment)
                    {
                        configUrl = "服务器IP,password=";
                    }
                    connectionMultiplexer = ConnectionMultiplexer.Connect(configUrl);
                    server = connectionMultiplexer.GetServer(configUrl.Split(',')[0] + ":6379");
                    database = connectionMultiplexer.GetDatabase();
                }
            }
            catch
            {
                Init();
            }
        }

        private static JsonSerializerSettings jsonConfig = new JsonSerializerSettings()
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            NullValueHandling = NullValueHandling.Ignore
        };

        public static object Get(string key)
        {
            return Get(key);
        }

        public static T Get(string key)
        {
            try
            {
                var cacheValue = database.StringGet(key);
                var value = default(T);
                if (!cacheValue.IsNull)
                {
                    var cacheObject = JsonConvert.DeserializeObject>(cacheValue, jsonConfig);
                    if (!cacheObject.ForceOutofDate)
                        database.KeyExpire(key, new TimeSpan(0, 0, cacheObject.ExpireTime));
                    value = cacheObject.Value;
                }
                return value;
            }
            catch
            {
                return default(T);
            }
        }

        public static void Set(string key, object data, int cacheTime)
        {
            try
            {
                var jsonData = GetJsonData(data, timeOut, true);
                database.StringSet(key, jsonData, TimeSpan.FromMinutes(cacheTime));
            }
            catch { }
        }

        public static void Set(string key, object data, DateTime cacheTime)
        {
            try
            {
                var jsonData = GetJsonData(data, timeOut, true);
                database.StringSet(key, jsonData, cacheTime - DateTime.Now);
            }
            catch { }
        }

        public static void Set(string key, T data, int cacheSeconds)
        {
            try
            {
                var jsonData = GetJsonData(data, timeOut, true);
                database.StringSet(key, jsonData, TimeSpan.FromSeconds(cacheSeconds));
            }
            catch { }
        }

        public static void Set(string key, T data, DateTime cacheTime)
        {
            try
            {
                var jsonData = GetJsonData(data, timeOut, true);
                database.StringSet(key, jsonData, cacheTime - DateTime.Now);
            }
            catch { }
        }

        /// 
        /// 删除指定key
        /// 
        public static void Remove(string key)
        {
            try
            {
                database.KeyDelete(key);
            }
            catch { }
        }

        /// 
        /// 判断key是否存在
        /// 
        public static bool Exists(string key)
        {
            try
            {
                return database.KeyExists(key);
            }
            catch
            {
                return false;
            }
        }

        /// 
        /// 模糊查询获取所有key集合
        /// 
        public static List SearchKeys(string keyPatten)
        {
            var list = new List();
            var keys = server.Keys(0, keyPatten).ToList();
            foreach (var key in keys)
            {
                list.Add(key.ToString());
            }
            return list;
        }

        /// 
        /// 根据key模糊查询
        /// 
        public static List Searchs(string keyPatten, out List keys)
        {
            var list = new List();
            keys = new List();
            var allKeys = SearchKeys(keyPatten);
            foreach (var key in allKeys)
            {
                var item = Get(key);
                if (item != null)
                {
                    keys.Add(key);
                    list.Add(item);
                }
            }
            return list;
        }

        /// 
        /// 发布
        /// 
        public static long Publish(string channel, string msg)
        {
            return connectionMultiplexer.GetSubscriber().Publish(channel, msg);
        }

        /// 
        /// 订阅
        /// 
        public static void Subcribe(string subChannel, Action handler)
        {
            connectionMultiplexer.GetSubscriber().Subscribe(subChannel, handler);
        }

        /// 
        /// 异步订阅
        /// 
        public async static Task SubscribeAsync(string subChannel, Action handler)
        {
            await connectionMultiplexer.GetSubscriber().SubscribeAsync(subChannel, handler);
        }

        /// 
        /// 取消订阅
        /// 
        public static void Unsubscribe(string channel)
        {
            connectionMultiplexer.GetSubscriber().Unsubscribe(channel);
        }

        /// 
        /// 取消全部订阅
        /// 
        public static void UnsubscribeAll()
        {
            connectionMultiplexer.GetSubscriber().UnsubscribeAll();
        }

        private static string GetJsonData(object data, int cacheTime, bool forceOutOfDate)
        {
            var cacheObject = new CacheObject() { Value = data, ExpireTime = cacheTime, ForceOutofDate = forceOutOfDate };
            return JsonConvert.SerializeObject(cacheObject, jsonConfig);//序列化对象
        }

        private static string GetJsonData(T data, int cacheTime, bool forceOutOfDate)
        {
            var cacheObject = new CacheObject() { Value = data, ExpireTime = cacheTime, ForceOutofDate = forceOutOfDate };
            return JsonConvert.SerializeObject(cacheObject, jsonConfig);//序列化对象
        }
    }

    class CacheObject
    {
        public int ExpireTime { get; set; }

        public bool ForceOutofDate { get; set; }

        public T Value { get; set; }
    }
}



转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号