技术资讯

软件开发:C#开发中缓存的使用案例

TIME:2018-09-11

缓存的概念及优缺点在这里就不多做介绍,主要介绍一下使用的方法。

1.在ASP.NET中页面缓存的使用方法简单,只需要在aspx页的顶部加上一句声明即可:

 <%@ OutputCache Duration="100" VaryByParam="none" %>

Duration:缓存时间(秒为单位),必填属性

2.使用微软自带的类库System.Web.Caching

新手接触的话不建议直接使用微软提供的类库,因为这样对理解不够深刻。所以在这里我带大家自己写一套缓存操作方法,这样理解得更加清晰。

话不多说,代码开敲。

 

一、首先,先模拟数据来源。新建一个类,写一个数据操作方法(该方法耗时、耗资源)

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace Cache
{
    public class DataSource
    {
        /// <summary>
        /// 模拟从数据库读取数据
        /// 耗时、耗CPU
        /// </summary>
        /// <param name="count"></param>
        public static int GetDataByDB(int count)
        {
            Console.WriteLine("-------GetDataByDB-------");
            int result = 0;
            for (int i = count; i < 99999999; i++)
            {
                result += i;
            }
            Thread.Sleep(2000);
            return result;
        }
    }
}

 二、编写一个缓存操作类

2.1 构造一个字典型容器,用于存放缓存数据,权限设为private ,防止随意访问造成数据不安全性

 //缓存容器  private static Dictionary<string, object> CacheDictionary = new Dictionary<string, object>();

       2.2 构造三个方法(添加数据至缓存容器、从缓存容器获取数据、判断缓存是否存在)

复制代码
 /// <summary> /// 添加缓存 /// </summary> public static void Add(string key, object value)
        {
            CacheDictionary.Add(key, value);
        } /// <summary> /// 获取缓存 /// </summary> public static T Get<T>(string key)
        { return (T)CacheDictionary[key];
        } /// <summary> /// 判断缓存是否存在 /// </summary> /// <param name="key"></param> /// <returns></returns> public static bool Exsits(string key)
        { return CacheDictionary.ContainsKey(key);
        }
复制代码

三、程序入口编写测试方法

      3.1 先看一下普通情况不适用缓存,它的执行效率有多慢

复制代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cache
{ class Program
    { static void Main(string[] args)
        { for (int i = 1; i < 6; i++)
            {
                Console.WriteLine($"------第{i}次请求------"); int result = DataSource.GetDataByDB(666);
                Console.WriteLine($"第{i}次请求获得的数据为:{result}");
            }
        }
    }
}
复制代码