基于Senparc.CO2NET 缓存策略扩展的缓存使用方法

没啥说的,直接上代码

1、缓存  CacheFactory 实现:

//-----------------------------------------------------------------------
// <copyright file="CacheFactory.cs" company="FenSiShengHuo, Ltd.">
//     Copyright (c) 2018 , All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using Senparc.CO2NET.Cache;
using Senparc.Weixin.Cache;
using System;

namespace DotNet.WeChat.CommonService.Utilities
{
    using DotNet.MVC.Infrastructure.Models;
    /// <summary>
    ///  CacheFactory 基于
    ///
    /// 修改记录
    ///
    ///        2018-04-20 版本:1.0 JiShiYu 创建文件。
    ///
    /// <author>
    ///     <name>JiShiYu</name>
    ///     <date>2018-04-20</date>
    /// </author>
    /// </summary>
    public class CacheFactory
    {
        /// <summary>
        /// 缓存处理 Redis
        /// </summary>
        /// <param name="cacheKey">缓存的Key</param>
        /// <param name="proc">处理函数</param>
        /// <param name="isCache">是否从缓存取</param>
        /// <param name="refreshCache">是否强制刷新缓存</param>
        /// <param name="expireAt">什么时候过期</param>
        /// <returns></returns>
        public static HashSetCacheModel<T> Cache<T>(string cacheKey, Func<HashSetCacheModel<T>> proc,bool isCache = false, bool refreshCache = false)
        {
            HashSetCacheModel<T> result;
            if (!isCache)
            {
                result = proc();
            }
            else
            {
                IContainerCacheStrategy containerCache = LocalContainerCacheStrategy.Instance;
                IBaseObjectCacheStrategy baseCache = containerCache.BaseCacheStrategy();
                // 缓存
                if (baseCache.CheckExisted(cacheKey)) //判断是否有缓存
                {
                    //已经缓存
                    if (refreshCache)//是否强制刷新缓存
                    {
                        //强制刷新
                        result = proc();
                        baseCache.Update(cacheKey, result);
                    }
                    else
                    {
                        //不强制刷新
                        result = baseCache.Get<HashSetCacheModel<T>>(cacheKey);
                        // 判断是否过期了
                        if (result.ExpireAt < DateTime.Now)
                        {
                            result = proc();
                            baseCache.Update(cacheKey, result);
                        }
                    }
                }
                else
                {
                    // 缓存中没有数据 获取一次存入缓存
                    result = proc();
                    baseCache.Set(cacheKey, result);
                }
            }
            return result;
        }
    }
}
注意:Senparc 底层的Redis使用了HashSet数据结构

2、使用方法:注释里是以前的写法,使用CacheFactory后简化了操作
        /// <summary>
        /// 获取微信用户
        /// </summary>
        /// <param name="weixinAppId"></param>
        /// <param name="openId"></param>
        /// <param name="refresh"></param>
        /// <returns></returns>
        protected WechatUserEntity GetWechatUser(string weixinAppId, string openId, bool refresh = false)
        {
            WechatUserEntity wechatUserEntity = null;
            // 进行缓存
            try
            {
                string cacheKey = "WechatUser:" + weixinAppId + ":" + openId;
                HashSetCacheModel<WechatUserEntity> hashCacheModel= CacheFactory.Cache<WechatUserEntity>(cacheKey, () =>
                {
                    WechatUserManager wechatUserManager = new WechatUserManager();
                    wechatUserEntity = wechatUserManager.GetObjectByWechatAppIdByOpenId(weixinAppId, openId);
                    var cacheModel = new HashSetCacheModel<WechatUserEntity>();
                    cacheModel.CreateOn = DateTime.Now;
                    cacheModel.ExpireAt = DateTime.Now.AddMinutes(10);
                    cacheModel.Value = wechatUserEntity;
                    return cacheModel;
                });
                return hashCacheModel.Value;

                //IContainerCacheStrategy containerCache = LocalContainerCacheStrategy.Instance;
                //IBaseObjectCacheStrategy baseCache = containerCache.BaseCacheStrategy();
                //HashSetCacheModel<WechatUserEntity> cacheModel = null;
                //// 强制刷新缓存
                //if (refresh)
                //{
                //    if (baseCache.CheckExisted(key))
                //    {
                //        baseCache.RemoveFromCache(key);
                //    }
                //}
                //if (baseCache.CheckExisted(key))
                //{
                //    cacheModel = baseCache.Get<HashSetCacheModel<WechatUserEntity>>(key);
                //    if (cacheModel.ExpireAt < DateTime.Now)
                //    {
                //        // 过期了,要更新一次
                //        WechatUserManager wechatUserManager = new WechatUserManager();
                //        wechatUserEntity = wechatUserManager.GetObjectByWechatAppIdByOpenId(weixinAppId, openId);
                //        cacheModel = new HashSetCacheModel<WechatUserEntity>();
                //        cacheModel.CreateOn = DateTime.Now;
                //        cacheModel.ExpireAt = DateTime.Now.AddMinutes(10);
                //        cacheModel.Value = wechatUserEntity;
                //        baseCache.Update(key, cacheModel);
                //    }
                //    wechatUserEntity = cacheModel.Value;
                //}
                //else
                //{
                //    WechatUserManager wechatUserManager = new WechatUserManager();
                //    wechatUserEntity = wechatUserManager.GetObjectByWechatAppIdByOpenId(weixinAppId, openId);
                //    cacheModel = new HashSetCacheModel<WechatUserEntity>();
                //    cacheModel.CreateOn = DateTime.Now;
                //    cacheModel.ExpireAt = DateTime.Now.AddMinutes(10);
                //    cacheModel.Value = wechatUserEntity;
                //    baseCache.Set(key, cacheModel);
                //}
            }
            catch (Exception ex)
            {
                NLogHelper.Warn(ex, "GetCurrentAutoreplyInfo,weixinAppId=" + weixinAppId);
            }

            return wechatUserEntity;
        }


原文地址:https://www.cnblogs.com/hnsongbiao/p/9299190.html

时间: 2024-08-02 19:11:50

基于Senparc.CO2NET 缓存策略扩展的缓存使用方法的相关文章

【安卓中的缓存策略系列】安卓缓存策略之磁盘缓存DiskLruCache

安卓中的缓存包括两种情况即内存缓存与磁盘缓存,其中内存缓存主要是使用LruCache这个类,其中内存缓存我在[安卓中的缓存策略系列]安卓缓存策略之内存缓存LruCache中已经进行过详细讲解,如看官还没看过此博客,建议看官先去看一下. 我们知道LruCache可以让我们快速的从内存中获取用户最近使用过的Bitmap,但是我们无法保证最近访问过的Bitmap都能够保存在缓存中,像类似GridView等需要大量数据填充的控件很容易就会用完整个内存缓存.另外,我们的应用可能会被类似打电话等行为而暂停导

iOS网络加载图片缓存策略之ASIDownloadCache缓存优化

在我们实际工程中,很多情况需要从网络上加载图片,然后将图片在imageview中显示出来,但每次都要从网络上请求,会严重影响用户体验,为了不是每次显示都需要从网上下载数据,希望将图片放到本地缓存,因此我们需要一个好的的缓存策略,今天我将我在项目工程中的实际经验分享给大家,我这里主要介绍一下强大的ASIHTTPRequest的缓存策略,以及使用方法. AD: 在我们实际工程中,很多情况需要从网络上加载图片,然后将图片在imageview中显示出来,但每次都要从网络上请求,会严重影响用户体验,为了不

基于Alluxio内存文件系统的缓存策略

Alluxio是一种基于内存的分布式文件系统,支持不同的缓存替换策略,来替换内存中的文件快.Alluxio中的文件时以文件块形式组织,其中文件通过自己实现的inode数据结构记录文件属性并索引. 下面首先介绍几种不同的缓存策略,这些缓存策略被广泛的应用在web,数据库,文件系统中. 1 基于访问频率的缓存策略 这种缓存策略是根据缓存单位的(在Alluxio中是文件块Block)访问频率来进行缓存调度,最常用的策略是LFU(Least Frequently Used)策略.该策略每次淘汰访问频率最

Web开发基本准则-55实录-缓存策略

郑昀 创建于2013年2月 郑昀 最后更新于2013年10月26日 提纲: Web访问安全 缓存策略 存储介质连接池 业务降级 并发请求的处理 关键词: 会话串号,Cache-Control头域,缓存穿透,缓存集体失效,缓存重建,缓存雪崩,缓存永不过期,缓存计数器, 二,缓存策略 这里的“缓存”概念不只限于服务器端的“缓存”. 2.1.防会话串号 如果你收到一个投诉,说访问“我的个人中心”页面时进入其他人的帐号,至少订单列表上显示的不是自己的.此时,技术支持人员可以提三个问题,第一,对页面上显示

NSURLRequestCachePolicy 缓存策略

1> NSURLRequestUseProtocolCachePolicy = 0, 默认的缓存策略, 如果缓存不存在,直接从服务端获取.如果缓存存在,会根据response中的Cache-Control字段判断下一步操作,如: Cache-Control字段为must-revalidata, 则询问服务端该数据是否有更新,无更新的话直接返回给用户缓存数据,若已更新,则请求服务端. 2> NSURLRequestReloadIgnoringLocalCacheData = 1, 忽略本地缓存数

对Hibernate缓存策略的理解和应用

引自:http://www.blogjava.net/frostwood/archive/2010/01/06/308465.html Hibernate提供了三个级别的缓存策略:Session缓存(基本的事务级缓存),Query Cache(查询缓存),Seond-Level Cache(二级缓存) Session缓存(First-Level Cache):Session是Hibernate用于管理持久化对象的核心机制,它是针对持久性数据的事务级缓存.PersistenceContext中包括

ios 缓存策略

NSURLRequestCachePolicy 缓存策略 1> NSURLRequestUseProtocolCachePolicy = 0, 默认的缓存策略, 如果缓存不存在,直接从服务端获取.如果缓存存在,会根据response中的Cache-Control字段判断下一步操作,如: Cache-Control字段为must-revalidata, 则询问服务端该数据是否有更新,无更新的话直接返回给用户缓存数据,若已更新,则请求服务端. 2> NSURLRequestReloadIgnori

UIWebView的缓存策略,清除cookie

缓存策略 NSURLRequestCachePolicy NSURLRequestUseProtocolCachePolicy缓存策略定义在 web 协议实现中,用于请求特定的URL.是默认的URL缓存策略 Specifies that the caching logic defined in the protocol implementation, if any, is used for a particular URL load request. This is the default po

【安卓中的缓存策略系列】安卓缓存策略之综合应用ImageLoader实现照片墙的效果

在前面的[安卓缓存策略系列]安卓缓存之内存缓存LruCache和[安卓缓存策略系列]安卓缓存策略之磁盘缓存DiskLruCache这两篇博客中已经将安卓中的缓存策略的理论知识进行过详细讲解,还没看过这两篇博客的看官建议先去看一下,本博客将依据这些理论知识打造一个ImageLoader,实现照片墙的效果,关于照片墙的知识网上相关博客也很多,首先解释一下照片墙的概念:用一个GridView控件当作"墙",然后随着GridView的滚动将一张张照片贴在"墙"上,很显然因为