欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

NopCommerce学习(1) Caching

程序员文章站 2022-04-28 09:53:53
redis教程 http://www.runoob.com/redis/redis tutorial.html 下载地址:https://github.com/MSOpenTech/redis/releases。 将Redis发布包解压: 在目录下,添加start.bat文件(内容如下),以管理员权 ......

redis教程 http://www.runoob.com/redis/redis-tutorial.html
下载地址:https://github.com/MSOpenTech/redis/releases。
将Redis发布包解压:
在目录下,添加start.bat文件(内容如下),以管理员权限打开,启动Redis缓存

@echo off
cd /d %~dp0
redis-server.exe redis.windows.conf

在目录下,添加Controller.bat文件(内容如下),以管理员权限打开,cmd访问Redis缓存,项目命令看redis教程

@echo off
cd /d %~dp0
redis-cli.exe -h 127.0.0.1 -p 6379

以下代码及完整代码GitBub地址:https://github.com/heshengli/nop
CacheHelper代码:

public class CacheHelper
 {
        public static readonly string _RedisCachingConnectionString =ConfigurationManager.AppSettings["RedisCachingConnectionString"];
        private static readonly RedisCacheManager _RedisCacheManager;

        static CacheHelper()
        {
            //创建缓存
            if (!string.IsNullOrWhiteSpace(_RedisCachingConnectionString))
            {
                RedisConnectionWrapper RedisConnectionWrapper = new RedisConnectionWrapper(_RedisCachingConnectionString);
                _RedisCacheManager = new RedisCacheManager(RedisConnectionWrapper);
            }
        }

        /// <summary>
        ///     创建缓存项的文件
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="obj">object对象</param>
        public static void Insert(string key, object obj)
        {
            Insert(key, obj, 60);
        }

        /// <summary>
        ///     移除缓存项的文件
        /// </summary>
        /// <param name="key">缓存Key</param>
        public static void Remove(string key)
        {
            _RedisCacheManager.Remove(key);
        }

        /// <summary>
        ///     创建缓存项过期
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="obj">object对象</param>
        /// <param name="expires">过期时间(分钟)</param>
        public static void Insert(string key, object obj, int expires)
        {
            _RedisCacheManager.Set(key, obj, expires);
        }

        /// <summary>
        ///     获取缓存对象
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <returns>object对象</returns>
        public static object Get(string key)
        {
            if (string.IsNullOrEmpty(key)) return null;
            return _RedisCacheManager.Get<object>(key);
        }

        /// <summary>
        ///     获取缓存对象
        /// </summary>
        /// <typeparam name="T">T对象</typeparam>
        /// <param name="key">缓存Key</param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            return _RedisCacheManager.Get<T>(key);
        }
 }