이 클래스는 사용자 코드로 구성할 수 있습니다. 업데이트\제거 콜백, 지역, 모니터 등과 같은 다른 인터페이스와 더 많은 기능이 있습니다. 이를 사용하려면 System.Runtime.Caching 라이브러리를 가져와야 합니다. ASP.net 응용 프로그램에서도 사용할 수 있지만 수명을 직접 관리해야 합니다.
1.Net Framework 4.6 이상에서 설치가능
2.설치
NuGet 패캐지 관리에서 설치 및 참조 추가 확인
3.참조 확인
4. Simple Source
1 2 3 4 5 6 |
var cache = new System.Runtime.Caching.MemoryCache("MyTestCache"); cache["ObjectList"] = list; // add list = (List<object>)cache["ObjectList"]; // retrieve cache.Remove("ObjectList"); // remove |
5. Process diagram
6.DB
7. Insert Query
링크 : https://github.com/iammukeshm/RepositoryPatternWithCachingAndHangfire/blob/master/SampleCustomers.sql
1 2 3 4 5 6 7 8 9 10 11 12 |
insert into Customers (FirstName, LastName, Contact, Email, DateOfBirth) values ('Caressa', 'Walsh', '868-449-3013', 'cwalsh0@google.es', '3/23/1996'); insert into Customers (FirstName, LastName, Contact, Email, DateOfBirth) values ('Rhea', 'Andrichuk', '733-892-8926', 'randrichuk1@elpais.com', '12/11/1997'); insert into Customers (FirstName, LastName, Contact, Email, DateOfBirth) values ('Amelia', 'Epp', '247-422-8619', 'aepp2@spiegel.de', '7/16/1999'); insert into Customers (FirstName, LastName, Contact, Email, DateOfBirth) values ('Cesaro', 'Goodwin', '606-804-3382', 'cgoodwin3@salon.com', '8/16/1990'); insert into Customers (FirstName, LastName, Contact, Email, DateOfBirth) values ('Lira', 'Crookall', '320-145-2453', 'lcrookall4@g.co', '9/14/1996'); insert into Customers (FirstName, LastName, Contact, Email, DateOfBirth) values ('Tye', 'Collin', '548-245-2593', 'tcollin5@dailymail.co.uk', '4/9/1993'); insert into Customers (FirstName, LastName, Contact, Email, DateOfBirth) values ('Clare', 'Kelson', '324-249-1362', 'ckelson6@amazon.co.jp', '11/26/1992'); insert into Customers (FirstName, LastName, Contact, Email, DateOfBirth) values ('Wilmer', 'Swaite', '657-532-9884', 'wswaite7@addthis.com', '9/22/1990'); insert into Customers (FirstName, LastName, Contact, Email, DateOfBirth) values ('Delphine', 'Gasson', '392-230-1556', 'dgasson8@51.la', '8/7/1994'); insert into Customers (FirstName, LastName, Contact, Email, DateOfBirth) values ('Manon', 'Yeowell', '789-838-9532', 'myeowell9@jimdo.com', '10/11/1999'); |
8.WebService Call (DataSet)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using System.Web.Services; using System.Data; namespace WebService1 { public class Service1 : System.Web.Services.WebService { [WebMethod()] public DataSet GetProductCatalog() { // Return the complete DataSet (from the cache, if possible). //return Function.GetCache(); return CacheClass.GetCustomerDataSet(); } [WebMethod()] public string[] GetProductList() { // Get the customer table (from the cache if possible). DataTable dt = CacheClass.GetCustomerDataSet().Tables[0]; // Create an array that will hold the name of each customer. string[] names = new string[dt.Rows.Count]; // Fill the array. int i = 0; foreach (DataRow row in dt.Rows) { names[i] = row["FirstName"].ToString(); i += 1; } return names; } } } |
9.Cache Insert (DataSet)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
using System; using System.Data; using System.Data.SqlClient; using System.Runtime.Caching; namespace WebService1 { public class CacheClass { private static string _key = "Customers"; private static readonly MemoryCache _cache = MemoryCache.Default; //private static string connectionString = "Data Source=localhost;" + "Initial Catalog=Northwind;user ID=sa"; private static string connectionString = "Server=SQLOLEDB.1;Password=*******;Persist Security Info=True;User ID=MYID;Initial Catalog=MYDB;Data Source=MYCOM"; public static DataSet GetCustomerDataSet() { // Check for cached item. //DataSet ds = HttpContext.Current.Cache["Customers"] as DataSet; //_cache.Remove(_key); if (!(_cache.Get(_key) is DataSet ds)) { // Recreate the item. string SQL = "SELECT * FROM Customers"; // Create ADO.NET objects. SqlConnection con = new SqlConnection(connectionString); SqlCommand com = new SqlCommand(SQL, con); SqlDataAdapter adapter = new SqlDataAdapter(com); ds = new DataSet(); // Execute the command. try { con.Open(); adapter.Fill(ds, "Customers"); // Store the item in the cache (for 60 seconds). //Do what you need to do here. Database Interaction, Serialization,etc. var cacheItemPolicy = new CacheItemPolicy() { //Set your Cache expiration. AbsoluteExpiration = DateTime.Now.AddMinutes(60) }; _cache.Add(_key, ds, cacheItemPolicy); } catch (Exception err) { System.Diagnostics.Debug.WriteLine(err.ToString()); } finally { con.Close(); } } return _cache.Get(_key) as DataSet; } } } |
10.화면
11.Result
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/"> <string>Caressa</string> <string>Rhea</string> <string>Amelia</string> <string>Cesaro</string> <string>Lira</string> <string>Tye</string> <string>Clare</string> <string>Wilmer</string> <string>Delphine</string> <string>Manon</string> <string>Bev</string> <string>Lodovico</string> |
12.Cache Insert advance
Multi Cache, stored procedure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
using System; using System.Data; using System.Data.SqlClient; using System.Runtime.Caching; using System.Configuration; namespace ConsoleHostRule { class CacheClass { private static readonly MemoryCache _cache = MemoryCache.Default; private static double CacheTime = double.Parse(ConfigurationManager.AppSettings["CacheTime"]);//CacheTime private static string connectionString = ConfigurationManager.ConnectionStrings["Customers"].ToString();//connectionString public static DataSet GetCacheData(string _key) { if (!(_cache.Get(_key) is DataSet ds)) { ds = new DataSet(); try { using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = conn.CreateCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "cache_" + _key; //StoredProcedure Name SqlDataAdapter adapter = new SqlDataAdapter { SelectCommand = cmd }; conn.Open(); adapter.Fill(ds); cmd.Dispose(); conn.Close(); conn.Dispose(); } var cacheItemPolicy = new CacheItemPolicy() { //Set your Cache expiration. AbsoluteExpiration = DateTime.Now.AddMinutes(CacheTime) }; _cache.Add(_key, ds, cacheItemPolicy); } catch (Exception err) { System.Diagnostics.Debug.WriteLine(err.ToString()); } } return _cache.Get(_key) as DataSet; } } } |
source : https://stackoverflow.com/questions/41684213/looking-for-a-very-simple-cache-example?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
참조 : https://swconsulting.tistory.com/801