技术资讯
软件开发: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}"); } } } }
相关推荐
-
秦皇岛装修行业互联网营销的四个注重点
TIME: 2018-04-14 -
新建网站如何提高流量的五个有效步骤
TIME: 2009/6/15 -
秦皇岛网站制作费用分析
TIME: 2010/9/17 9:08:06 -
网站开发:MySQL安全优化
TIME: 2018-09-30 -
搜索引擎优化初学者必掌握的八项基本技能
TIME: 2009/6/8 -
轻松一刻(秦皇岛网络公司)
TIME: 2010/11/8 -
中小型网站的推广手段(上)
TIME: 2010/4/17 -
为什么要誓死学好 Redis ?
TIME: 2018-03-31 -
这种网站多做几个也值了!
TIME: 2012/6/14 -
企业网站优化时最容易出现的错误
TIME: 2009/6/8 -
区块链到底是什么鬼?有哪些网络应用?
TIME: 2018-03-29 -
网络开发之区块链开发入门
TIME: 2018-08-18