• Redis缓存公共方法类


    Redis缓存公共方法类

    Config配置文件:

        <!--Redis相关设置-->
        <!--是否打开缓存1是0否-->
        <add key="IsOpenCache" value="1" />
        <!--redis IP地址-->
        <add key="RedisIP" value="192.168.1.1" />
        <!--redis端口(不填默认6379)-->
        <add key="RedisPort" value="6379" />
        <!--redis密码(不填表示没有密码)-->
        <add key="RedisPassword" value="@123456" />
        <!--redis库索引号(整数,默认有5个库,从0开始,不填表示0)-->
        <add key="RedisDb" value="2" />
        <!--Redis相关设置结束  -->
        <add key="ClientSettingsProvider.ServiceUri" value="" />
    View Code

    RedisHelper:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using ServiceStack.Redis;
    
    public class RedisHelper
    {
        private static object lockobj = new object();
        /// <summary>
        /// 加入缓存
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="cacheKey">Key(键值命名规范:RK_字段名_表名_条件字段1_值_条件字段n_值......,键值全部小写,表名不加dbo前缀)</param>
        /// <param name="obj">对象</param>
        /// <param name="expiresAt">缓存时间(除了XianZhiAccounts的过期时间为一小时,其余的过期时间都为两天)</param>
        /// <returns>是否缓存成功</returns>
        public static bool Set<T>(string cacheKey, T obj, DateTime expiresAt)
        {
            bool result = false;
            lock (lockobj)
            {
                try
                {
                    if (IsOpenCache)
                    {
                        if (!(obj is System.Data.DataTable) || !(obj is System.Data.DataSet) || !(obj is System.Data.DataRow))
                        {
                            using (IRedisClient Redis = prcm.GetClient())
                            {
                                result = Redis.Set<T>(cacheKey, obj, expiresAt);
                            }
                        }
                    }
                }
                catch { }
            }
            return result;
        }
    
        /// <summary>
        /// 加入缓存(永久缓存)
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="cacheKey">Key(键值命名规范:RK_字段名_表名_条件字段1_值_条件字段n_值......,键值全部小写)</param>
        /// <param name="obj">对象</param>
        /// <returns>是否缓存成功</returns>
        private static bool Set<T>(string cacheKey, T obj)
        {
            lock (lockobj)
            {
                try
                {
                    if (!IsOpenCache) return false;
                    return Set<T>(cacheKey, obj, DateTime.Now.AddYears(100));
                }
                catch { return false; }
            }
        }
    
        /// <summary>
        /// 获取缓存内容
        /// </summary>
        /// <param name="cacheKey">Key</param>
        /// <returns></returns>
        public static T Get<T>(string cacheKey)
        {
            lock (lockobj)
            {
                try
                {
                    if (!IsOpenCache) return default(T);
                    using (IRedisClient Redis = prcm.GetClient())
                    {
                        return Redis.Get<T>(cacheKey);
                    }
                }
                catch
                {
                    string str = string.Empty;
                    return default(T);
                }
            }
        }
    
    
        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="cacheKey">Key</param>
        /// <returns></returns>
        public static bool Del(string cacheKey)
        {
            try
            {
                if (!IsOpenCache) return false;
                using (IRedisClient Redis = prcm.GetClient())
                {
                    return Redis.Remove(cacheKey);
                }
            }
            catch { return false; }
        }
    
        /// <summary>
        /// 批量删除缓存
        /// </summary>
        /// <param name="cacheKeys">Key</param>
        /// <returns></returns>
        public static void Del(List<string> cacheKeys)
        {
            try
            {
                if (!IsOpenCache) return;
                using (IRedisClient Redis = prcm.GetClient())
                {
                    Redis.RemoveAll(cacheKeys);
                }
            }
            catch { return; }
        }
    
        /// <summary>
        /// 清空缓存
        /// </summary>
        public static void ClearCache()
        {
            try
            {
                if (!IsOpenCache) return;
                using (IRedisClient Redis = prcm.GetClient())
                {
                    Redis.FlushAll();
                }
            }
            catch { return; }
        }
    
    
    
        #region 私有方法
    
        private static string RedisIP = ConfigHelper.GetAppSettingValue("RedisIP");
        private static string RedisPassword = ConfigHelper.GetAppSettingValue("RedisPassword");
        private static int RedisPort = _51Sole.DJG.Common.DataConvert.ToInt(ConfigHelper.GetAppSettingValue("RedisIP"), 6379);
        private static int DbIndex = _51Sole.DJG.Common.DataConvert.ToInt(ConfigHelper.GetAppSettingValue("RedisDb"), 2);
    
        private static PooledRedisClientManager prcm = CreateManager(
            new string[] { "" + RedisPassword + "@" + RedisIP + ":" + RedisPort + " " },
            new string[] { "" + RedisPassword + "@" + RedisIP + ":" + RedisPort + " " });
    
        private static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)
        {
            // 支持读写分离,均衡负载 
            RedisClientManagerConfig clientConfig = new RedisClientManagerConfig();
    
            clientConfig.MaxWritePoolSize = 10000;
            clientConfig.MaxReadPoolSize = 10000;
            clientConfig.AutoStart = true;
            clientConfig.DefaultDb = DbIndex;
            
            PooledRedisClientManager clientManager = new PooledRedisClientManager(readWriteHosts, readOnlyHosts, clientConfig);
            return clientManager;
        }
    
        /// <summary>
        /// 是否使用缓存开关
        /// </summary>
        private static bool IsOpenCache
        {
            get
            {
                if (ConfigHelper.GetAppSettingValue("IsOpenCache") != "1") return false;
                return true;
            }
        }
    
        #endregion
    }
    View Code

    ConfigHelper:

    /// <summary>
    /// Redis配置文件帮助类
    /// </summary>
    public class ConfigHelper
    {
    
        #region 配置文件读取
    
    
        public static string GetAppSettingValue(string key)
        {
            try
            {
                return System.Configuration.ConfigurationManager.AppSettings[key];
            }
            catch
            {
                return string.Empty;
            }
        }
    
        #endregion
    
    }
    View Code

    TypeConverter:

    using System;
    using System.Globalization;
    
    public class TypeConverter
    {
    
        /// <summary>
        /// 转换为int类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue">返回的默认值</param>
        /// <param name="numStyle">数字格式</param>
        /// <returns></returns>
        public static int ConvertToInt(object obj, NumberStyles numStyle)
        {
            int result = 0;
            if (obj != null && obj != DBNull.Value)
            {
                if (!int.TryParse(obj.ToString().Trim(), numStyle, null, out result))
                {
                    result = 0;
                }
            }
            return result;
    
        }
        /// <summary>
        /// 转换为int类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue">返回的默认值</param>
        /// <returns></returns>
        public static int ConvertToInt(object obj)
        {
            return ConvertToInt(obj, NumberStyles.Number);
        }
    }
    View Code

    添加缓存方法:

    string keyWord = "TestRedis";
    string cacheKey_keyWord = "RK_RedisCache_KeyWord_" + keyWord;
    string cacheKey_Data = "RK_RedisCache_Data_" + keyWord;
    
     RedisHelper.Set<string>(cacheKey_keyWord, "此处放缓存值", DateTime.Now.AddDays(5));//有效期
    View Code
    如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!
    版权声明:本文原创发表于 博客园,作者为 码农-小菜鸟 本文欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则视为侵权。
  • 相关阅读:
    ./是当前目录 ../是当前的上一级目录。上上级就是../../一般绝对路径时候常用
    java web 代码
    java特点
    KVC
    架构设计:前后端分离之Web前端架构设计
    从MVC到前后端分离
    you don't have permission 错误
    为什么Tomcat的webapps目录下新建的目录不能访问html文件?
    UTF-8编码规则(转)
    Delphi 有关的网址
  • 原文地址:https://www.cnblogs.com/xiaoxiaocainia/p/5706912.html
Copyright © 2020-2023  润新知