服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#中缓存的基本使用方法

C#中缓存的基本使用方法

2022-02-28 14:27王继峰 C#

项目开发过程中缓存的应用到处可见,下面这篇文章主要给大家介绍了关于C#中缓存的基本使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习

前言

缓存主要是为了提高数据的读取速度。因为服务器和应用客户端之间存在着流量的瓶颈,所以读取大容量数据时,使用缓存来直接为客户端服务,可以减少客户端与服务器端的数据交互,从而大大提高程序的性能。

缓存这个东西可大可小,小到一个静态的字段,大到将整个数据库cache起来。项目开发过程中缓存的应用到处可见,本文主要介绍一下使用的方法,下面话不多说了,来一起看看详细的介绍吧

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

?
1
<%@ 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 ,防止随意访问造成数据不安全性

?
1
2
//缓存容器
private static dictionary<string, object> cachedictionary = new dictionary<string, object>();

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

?
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
/// <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 先看一下普通情况不适用缓存,它的执行效率有多慢

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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}");
  }
 }
 }
}

C#中缓存的基本使用方法

3.2 接下来,我们编写缓存试用方法。概念无非就是根据key前往字典容器里查找是否有相对应缓存数据,有则直接调用,没有则生成并存入字典容器里。

?
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
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);
    int result = 0;
    //key的名字一定要确保请求的准确性 datasource getdatabydb 666缺一不可
    string key = "datasource_getdatabydb_666";
    if (cachehelper.exsits(key))
    {
     //缓存存在,直接获取原数据
     result = cachehelper.get<int>(key);
    }
    else
    {
     //缓存不存在,去生成缓存,并加入容器
     result = datasource.getdatabydb(666);
     cachehelper.add(key, result);
    }
    console.writeline($"第{i}次请求获得的数据为:{result}");
   }
  }
 }
}

 3.3 我们看看加入缓存之后的效率如何

C#中缓存的基本使用方法

四、可以看到,瞬间完成。事已至此,缓存的使用基本是完成了。但是回过头来我们想想看。一个系统成百上千个地方使用缓存的话,那岂不是要写成百上千个if else判断缓存是否存在,然后获取?

答案显而易见,肯定不合理的。所以我们要对代码进行优化。

4.1 缓存操作类(cachehelper)编写一个通用的获取方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/// <summary>
  /// 缓存获取方法
  /// </summary>
  /// <typeparam name="t"></typeparam>
  /// <param name="key">缓存字典容器对应key</param>
  /// <param name="func">委托方法 传入操作对象</param>
  /// <returns></returns>
  public static t getcache<t>(string key, func<t> func)
  {
   t t = default(t);
   if (cachehelper.exsits(key))
   {
    //缓存存在,直接获取原数据
    t = cachehelper.get<t>(key);
   }
   else
   {
    //缓存不存在,去生成缓存,并加入容器
    t = func.invoke();
    cachehelper.add(key, t);
   }
   return t;
  }

4.2 程序入口进行调用,传入的委托参数为lamad表达式优化后的代码

?
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
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 = 0;
    //key的名字一定要确保请求的准确性 datasource getdatabydb 666缺一不可
    string key = "datasource_getdatabydb_666";
 
    //将需要执行的获取数据操作编写成委托传入方法(重点)
    //func<int> func = new func<int>(() => { return datasource.getdatabydb(666); });
 
    result = cachehelper.getcache(key, () => datasource.getdatabydb(666));
    console.writeline($"第{i}次请求获得的数据为:{result}");
   }
  }
 }
}

到这里,缓存的使用基本结束了。最好值得一提的是,缓存尽量在数据量小、重复查询量大的情况下使用。因为缓存也是要耗内存的,服务器内存是有限的!

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://www.cnblogs.com/wangjifeng23/p/9626119.html

延伸 · 阅读

精彩推荐
  • C#深入理解C#的数组

    深入理解C#的数组

    本篇文章主要介绍了C#的数组,数组是一种数据结构,详细的介绍了数组的声明和访问等,有兴趣的可以了解一下。...

    佳园9492021-12-10
  • C#三十分钟快速掌握C# 6.0知识点

    三十分钟快速掌握C# 6.0知识点

    这篇文章主要介绍了C# 6.0的相关知识点,文中介绍的非常详细,通过这篇文字可以让大家在三十分钟内快速的掌握C# 6.0,需要的朋友可以参考借鉴,下面来...

    雨夜潇湘8272021-12-28
  • C#VS2012 程序打包部署图文详解

    VS2012 程序打包部署图文详解

    VS2012虽然没有集成打包工具,但它为我们提供了下载的端口,需要我们手动安装一个插件InstallShield。网上有很多第三方的打包工具,但为什么偏要使用微软...

    张信秀7712021-12-15
  • C#SQLite在C#中的安装与操作技巧

    SQLite在C#中的安装与操作技巧

    SQLite,是一款轻型的数据库,用于本地的数据储存。其优点有很多,下面通过本文给大家介绍SQLite在C#中的安装与操作技巧,感兴趣的的朋友参考下吧...

    蓝曈魅11162022-01-20
  • C#C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    这篇文章主要介绍了C#设计模式之Strategy策略模式解决007大破密码危机问题,简单描述了策略模式的定义并结合加密解密算法实例分析了C#策略模式的具体使用...

    GhostRider10972022-01-21
  • C#如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    这篇文章主要给大家介绍了关于如何使用C#将Tensorflow训练的.pb文件用在生产环境的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴...

    bbird201811792022-03-05
  • C#利用C#实现网络爬虫

    利用C#实现网络爬虫

    这篇文章主要介绍了利用C#实现网络爬虫,完整的介绍了C#实现网络爬虫详细过程,感兴趣的小伙伴们可以参考一下...

    C#教程网11852021-11-16
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127762021-11-25