c# .Net 緩存 使用System.Runtime.Caching 做緩存 平滑過期,絕對過期

  1 public class CacheHeloer
  2 {
  3 
  4     /// <summary>
  5     /// 默認緩存
  6     /// </summary>
  7     private static CacheHeloer Default { get { return new CacheHeloer(); } }
  8 
  9     /// <summary>
 10     /// 緩存初始化
 11     /// </summary>
 12     private MemoryCache cache = MemoryCache.Default;
 13 
 14     /// <summary>
 15     /// 16     /// </summary>
 17     private object locker = new object();
 18 
 19     /// <summary>
 20     /// 構造器
 21     /// </summary>
 22     private CacheHeloer()
 23     {
 24         //CacheItemPolicy policy = new CacheItemPolicy();  //創建緩存項策略
 25         ////過期時間設置,以下兩種只能設置一種
 26         //policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(5)); //設定某個時間過后將逐出緩存
 27         //policy.SlidingExpiration = new TimeSpan(0, 0, 10);    //設定某個時間段內未被訪問將逐出緩存
 28         ////逐出通知,以下兩種只能設置一種
 29         //policy.UpdateCallback = arguments => { Console.WriteLine("即將逐出緩存" + arguments.Key); };
 30     }
 31 
 32     /// <summary>
 33     /// 從緩存中獲取對象
 34     /// </summary>
 35     /// <typeparam name="T">對象類型</typeparam>
 36     /// <param name="key"></param>
 37     /// <returns>緩存對象</returns>
 38     public static object Get(string key)
 39     {
 40         return Default.GetFromCache(key);
 41     }
 42 
 43     /// <summary>
 44     /// 從緩存中獲取對象
 45     /// </summary>
 46     /// <typeparam name="T">對象類型</typeparam>
 47     /// <param name="key"></param>
 48     /// <returns>緩存對象</returns>
 49     private object GetFromCache(string key)
 50     {
 51         lock (locker)
 52         {
 53             if (cache.Contains(key))
 54             {
 55                 return cache[key];
 56             }
 57             return null;
 58         }
 59     }
 60 
 61     /// <summary>
 62     /// 設置緩存指定時間未訪問過期
 63     /// </summary>
 64     /// <typeparam name="T">對象</typeparam>
 65     /// <param name="key"></param>
 66     /// <param name="value">數據對象</param>
 67     /// <param name="expire">過期時間</param>
 68     public static bool Set(string key, Object value, TimeSpan expiresIn)
 69     {
 70         var policy = new CacheItemPolicy()
 71         {
 72             SlidingExpiration = expiresIn
 73         };
 74         return Default.SetToCache(key, value, policy);
 75     }
 76     /// <summary>
 77     /// 設置緩存絕對時間過期
 78     /// </summary>
 79     /// <typeparam name="T"></typeparam>
 80     /// <param name="key"></param>
 81     /// <param name="value"></param>
 82     /// <param name="expiresIn"></param>
 83     /// <returns></returns>
 84     public static bool Set(string key, Object value, DateTimeOffset expiresIn)
 85     {
 86         var policy = new CacheItemPolicy()
 87         {
 88             AbsoluteExpiration = expiresIn
 89         };
 90         return Default.SetToCache(key, value, policy);
 91     }
 92 
 93     /// <summary>
 94     /// 添加到緩存
 95     /// </summary>
 96     /// <typeparam name="T">緩存對象類型</typeparam>
 97     /// <param name="key"></param>
 98     /// <param name="value"></param>
 99     /// <returns>結果狀態</returns>
100     public static bool Set(string key, object value)
101     {
102         CacheItemPolicy policy = new CacheItemPolicy()
103         {
104             Priority = CacheItemPriority.NotRemovable,
105         };
106         return Default.SetToCache(key, value, policy);
107     }
108 
109     /// <summary>
110     /// 數據對象裝箱緩存
111     /// </summary>
112     /// <typeparam name="T">對象</typeparam>
113     /// <param name="key"></param>
114     /// <param name="value">數據對象</param>
115     /// <param name="expire">過期時間</param>
116     private bool SetToCache(string key, object value, CacheItemPolicy policy)
117     {
118         lock (locker)
119         {
120             cache.Set(key, value, policy);
121             return true;
122         }
123     }
124 
125     /// <summary>
126     /// 獲取鍵的集合
127     /// </summary>
128     /// <returns>鍵的集合</returns>
129     public static ICollection<string> Keys()
130     {
131         return Default.GetCacheKeys();
132     }
133 
134     /// <summary>
135     /// 獲取鍵的集合
136     /// </summary>
137     /// <returns>鍵的集合</returns>
138     private ICollection<string> GetCacheKeys()
139     {
140         lock (locker)
141         {
142             IEnumerable<KeyValuePair<string, object>> items = cache.AsEnumerable();
143             return items.Select(m => m.Key).ToList();
144         }
145     }
146 
147     /// <summary>
148     /// 判斷緩存中是否有此對象
149     /// </summary>
150     /// <param name="key"></param>
151     /// <returns>是否存在</returns>
152     public static bool Contain(string key)
153     {
154         return Default.ContainKey(key);
155     }
156 
157     /// <summary>
158     /// 判斷緩存中是否有此對象
159     /// </summary>
160     /// <param name="key"></param>
161     /// <returns>是否存在</returns>
162     private bool ContainKey(string key)
163     {
164         lock (locker)
165         {
166             return cache.Contains(key);
167         }
168     }
169 
170     /// <summary>
171     /// 數據對象從緩存對象中移除
172     /// </summary>
173     /// <param name="key"></param>
174     public static bool Remove(string key)
175     {
176         return Default.RemoveFromCache(key);
177     }
178 
179     /// <summary>
180     /// 數據對象從緩存對象中移除
181     /// </summary>
182     /// <param name="key"></param>
183     private bool RemoveFromCache(string key)
184     {
185         lock (locker)
186         {
187             if (cache.Contains(key))
188             {
189                 cache.Remove(key);
190                 return true;
191             }
192             return false;
193         }
194     }
195 
196     /// <summary>
197     /// 清除實例
198     /// </summary>
199     public static void Clear()
200     {
201         Default.ClearCache();
202     }
203 
204     /// <summary>
205     /// 清除實例
206     /// </summary>
207     private void ClearCache()
208     {
209         lock (locker)
210         {
211             cache.ToList().ForEach(m => cache.Remove(m.Key));
212         }
213     }
214 
215     /// <summary>
216     /// 獲取緩存對象集合
217     /// </summary>
218     /// <typeparam name="T">緩存對象類型</typeparam>
219     /// <returns>緩存對象集合</returns>
220     public static ICollection<T> Values<T>()
221     {
222         return Default.GetValues<T>();
223     }
224 
225     /// <summary>
226     /// 獲取緩存對象集合
227     /// </summary>
228     /// <typeparam name="T">緩存對象類型</typeparam>
229     /// <returns>緩存對象集合</returns>
230     private ICollection<T> GetValues<T>()
231     {
232         lock (locker)
233         {
234             IEnumerable<KeyValuePair<string, object>> items = cache.AsEnumerable();
235             return items.Select(m => (T)m.Value).ToList();
236         }
237     }
238 
239     /// <summary>
240     /// 獲取緩存尺寸
241     /// </summary>
242     /// <returns>緩存尺寸</returns>
243     public static long Size()
244     {
245         return Default.GetCacheSize();
246     }
247 
248     /// <summary>
249     /// 獲取緩存尺寸
250     /// </summary>
251     /// <returns>緩存尺寸</returns>
252     private long GetCacheSize()
253     {
254         lock (locker)
255         {
256             return cache.GetCount();
257         }
258     }
259 }

?

轉載于:https://www.cnblogs.com/aaaaq/p/8552320.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391037.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391037.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391037.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python 實現分步累加_Python網頁爬取分步指南

python 實現分步累加As data scientists, we are always on the look for new data and information to analyze and manipulate. One of the main approaches to find data right now is scraping the web for a particular inquiry.作為數據科學家&#xff0c;我們一直在尋找…

Java 到底有沒有析構函數呢?

Java 到底有沒有析構函數呢&#xff1f; ? ? Java 到底有沒有析構函數呢&#xff1f;我沒能找到任何有關找個的文檔。如果沒有的話&#xff0c;我要怎么樣才能達到一樣的效果&#xff1f; ? ? ? 為了使得我的問題更加具體&#xff0c;我寫了一個應用程序去處理數據并且說…

關于雙黑洞和引力波,LIGO科學家回答了這7個你可能會關心的問題

引力波的成功探測&#xff0c;就像雙黑洞的碰撞一樣&#xff0c;一石激起千層浪。 關于雙黑洞和引力波&#xff0c;LIGO科學家回答了這7個你可能會關心的問題 最近&#xff0c;引力波的成功探測&#xff0c;就像雙黑洞的碰撞一樣&#xff0c;一石激起千層浪。 大家興奮之余&am…

如何使用HTML,CSS和JavaScript構建技巧計算器

A Tip Calculator is a calculator that calculates a tip based on the percentage of the total bill.小費計算器是根據總賬單的百分比計算小費的計算器。 Lets build one now.讓我們現在建立一個。 第1步-HTML&#xff1a; (Step 1 - HTML:) We create a form in order to…

用于MLOps的MLflow簡介第1部分:Anaconda環境

在這三部分的博客中跟隨了演示之后&#xff0c;您將能夠&#xff1a; (After following along with the demos in this three part blog you will be able to:) Understand how you and your Data Science teams can improve your MLOps practices using MLflow 了解您和您的數…

[WCF] - 使用 [DataMember] 標記的數據契約需要聲明 Set 方法

WCF 數據結構中返回的只讀屬性 TotalCount 也需要聲明 Set 方法。 [DataContract]public class BookShelfDataModel{ public BookShelfDataModel() { BookList new List<BookDataModel>(); } [DataMember] public List<BookDataModel>…

sql注入語句示例大全_SQL Group By語句用示例語法解釋

sql注入語句示例大全GROUP BY gives us a way to combine rows and aggregate data.GROUP BY為我們提供了一種合并行和匯總數據的方法。 The data used is from the campaign contributions data we’ve been using in some of these guides.使用的數據來自我們在其中一些指南…

ConcurrentHashMap和Collections.synchronizedMap(Map)的區別是什么?

ConcurrentHashMap和Collections.synchronizedMap(Map)的區別是什么&#xff1f; 我有一個會被多個線程同時修改的Map 在Java的API里面&#xff0c;有3種不同的實現了同步的Map實現 HashtableCollections.synchronizedMap(Map)ConcurrentHashMap 據我所知&#xff0c;HashT…

pymc3 貝葉斯線性回歸_使用PyMC3估計的貝葉斯推理能力

pymc3 貝葉斯線性回歸內部AI (Inside AI) If you’ve steered clear of Bayesian regression because of its complexity, this article shows how to apply simple MCMC Bayesian Inference to linear data with outliers in Python, using linear regression and Gaussian ra…

Hadoop Streaming詳解

一&#xff1a; Hadoop Streaming詳解 1、Streaming的作用 Hadoop Streaming框架&#xff0c;最大的好處是&#xff0c;讓任何語言編寫的map, reduce程序能夠在hadoop集群上運行&#xff1b;map/reduce程序只要遵循從標準輸入stdin讀&#xff0c;寫出到標準輸出stdout即可 其次…

mongodb分布式集群搭建手記

一、架構簡介 目標 單機搭建mongodb分布式集群(副本集 分片集群)&#xff0c;演示mongodb分布式集群的安裝部署、簡單操作。 說明 在同一個vm啟動由兩個分片組成的分布式集群&#xff0c;每個分片都是一個PSS(Primary-Secondary-Secondary)模式的數據副本集&#xff1b; Confi…

歸約歸約沖突_JavaScript映射,歸約和過濾-帶有代碼示例的JS數組函數

歸約歸約沖突Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. In this article, you will learn why …

為什么Java里面的靜態方法不能是抽象的

為什么Java里面的靜態方法不能是抽象的&#xff1f; 問題是為什么Java里面不能定義一個抽象的靜態方法&#xff1f;例如&#xff1a; abstract class foo {abstract void bar( ); // <-- this is okabstract static void bar2(); //<-- this isnt why? }回答一 因為抽…

python16_day37【爬蟲2】

一、異步非阻塞 1.自定義異步非阻塞 1 import socket2 import select3 4 class Request(object):5 def __init__(self,sock,func,url):6 self.sock sock7 self.func func8 self.url url9 10 def fileno(self): 11 return self.soc…

樸素貝葉斯實現分類_關于樸素貝葉斯分類及其實現的簡短教程

樸素貝葉斯實現分類Naive Bayes classification is one of the most simple and popular algorithms in data mining or machine learning (Listed in the top 10 popular algorithms by CRC Press Reference [1]). The basic idea of the Naive Bayes classification is very …

python:改良廖雪峰的使用元類自定義ORM

概要本文僅僅是對廖雪峰老師的使用元類自定義ORM進行改進&#xff0c;并不是要創建一個ORM框架 編寫fieldclass Field(object):def __init__(self, column_type,max_length,**kwargs):1&#xff0c;刪除了參數name&#xff0c;field參數全部為定義字段類型相關參數&#xff0c;…

2019年度年中回顧總結_我的2019年回顧和我的2020年目標(包括數量和收入)

2019年度年中回顧總結In this post were going to take a look at how 2019 was for me (mostly professionally) and were also going to set some goals for 2020! &#x1f929; 在這篇文章中&#xff0c;我們將了解2019年對我來說(主要是職業)如何&#xff0c;我們還將為20…

在Java里重寫equals和hashCode要注意什么問題

問題&#xff1a;在Java里重寫equals和hashCode要注意什么問題 重寫equals和hashCode有哪些問題或者陷阱需要注意&#xff1f; 回答一 理論&#xff08;對于語言律師或比較傾向于數學的人&#xff09;&#xff1a; equals() (javadoc) 必須定義為一個相等關系&#xff08;它…

vray陰天室內_陰天有話:第1部分

vray陰天室內When working with text data and NLP projects, word-frequency is often a useful feature to identify and look into. However, creating good visuals is often difficult because you don’t have a lot of options outside of bar charts. Lets face it; ba…

【codevs2497】 Acting Cute

這個題個人認為是我目前所做的最難的區間dp了&#xff0c;以前把環變成鏈的方法在這個題上并不能使用&#xff0c;因為那樣可能存在重復計算 我第一遍想的時候就是直接把環變成鏈了&#xff0c;wa了5個點&#xff0c;然后仔細思考一下就發現了問題 比如這個樣例 5 4 1 2 4 1 1 …