1, 概述
系统性能优化的第一步就是使用缓存! 什么是缓存? 缓存是一种效果, 就是把数据结果存在某个介质中, 下次直接重用. 根据二八原则, 80% 的请求都集中在 20% 的数据上, 缓存就是把 20% 的数据存起来, 直接复用. web 系统缓存主要分为客户端缓存, CDN 缓存, 反向代理缓存及服务器缓存, 而服务器缓存又分类本地缓存, 分布式缓存. 本节将给大家分享. Net Core 跨平台开发 服务器缓存开发实战.
2, 项目创建 - ShiQuan.WebTest
-》创建 ASP.NET Core3.1 Web 项目 - shiquan.webtest, 添加默认控制器 - DefaultController .
开发环境使用 VS2019 aps.NET core 3.1
-》Action Index 方法
- public IActionResult Index()
- {
- /*Web 服务器响应请求时, 设置缓存 Cache-Control. 单位为秒.*/
- //base.HttpContext.Response.Headers[HeaderNames.CacheControl] = "public,max-age=600";//no-cache
- base.ViewBag.Now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff");
- base.ViewBag.Url = $"{base.Request.Scheme}://{base.Request.Host}";// 浏览器地址
- base.ViewBag.InternalUrl = $"{base.Request.Scheme}://:{this._iConfiguration["port"]}";// 应用程序地址
- return View();
- }
-》在 Startup 文件的 Configure, 使用 UseStaticFile 指定当前路径.
- // 使用 UseStaticFile 指定当前路径
- App.UseStaticFiles(new StaticFileOptions()
- {
- FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot"))
- });
-》复制 wwwroot 目录及文件到 debug\bin 目录.
-》在 Program 文件中配置命令行获取参数.
- public static void Main(string[] args)
- {
- // 配置命令行获取参数
- new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddCommandLine(args)// 支持命令行参数
- .Build();
- CreateHostBuilder(args).Build().Run();
- }
-》使用控制台, 启动 Web 项目 - dotnet shiquan.webtest.dll --urls=http://*:5177 --port=5177.
-》运行效果
3, 本地缓存 - MemoryCache
下面我们来进行本地缓存 - MemoryCache 的开发, 首先安装 MemoryCache 安装包
-》Startup 配置添加 MemoryCache 的使用.
-》本地缓存的调用
- var key = "defaultcontroller_info";
- # region 服务器本地缓存 - MemoryCache
- {
- var time = string.Empty;
- if(this._iMemoryCache.TryGetValue(key,out time) == false)
- {
- time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff");
- this._iMemoryCache.Set(key, time);
- }
- base.ViewBag.MemoryCacheNew = time;
- }
- #endregion
-》Info 页面内容
- @{
- ViewData["Title"] = "Home Page";
- }
- <div>
- <h1>Index</h1>
- <h2 > 浏览器地址:@base.ViewBag.Url</h2>
- <h2 > 服务器地址:@base.ViewBag.InternalUrl</h2>
- <h2 > 后台 Action 时间:@base.ViewBag.Now</h2>
- <h2>MemoryCache 时间:@base.ViewBag.MemoryCacheNew</h2>
- <h2>RedisCache 时间:@base.ViewBag.RedisCacheNow</h2>
- <h2>CustomCache 时间:@base.ViewBag.CustomCacheNow</h2>
- <h2 > 前端 View 时间:@DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")</h2>
- </div>
-》运行效果, 后台 Action 及前端 View 时间, 每次刷新都会更新, 而内存缓存首次加载后, 都将保存原有时间.
4, 分布式缓存 - DistributedCache
我们使用 Redis 作为分布式缓存数据库, 首先下载安装配置 Redis 数据库, Redis 数据库默认端口: 6379.
-》在. Net core 项目中添加 Microsoft.Extensions.Caching.Redis 安装包
-》在 Startup 文件中配置分布式缓存
- /* 增加分布式缓存 Redis*/
- services.AddDistributedRedisCache(option => {
- option.Configuration = "127.0.0.1:6379";
- option.InstanceName = "DistributedRedisCache";
- });
-》控制器调用分布式缓存, 实现内容保存与读取, 在页面中显示.
- #region 分布式缓存 - 解决缓存在不同实例共享问题
- {
- var time = this._iRedisCache.GetString(key);
- if (string.IsNullOrEmpty(time))
- {
- time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff");
- this._iRedisCache.SetString(key, time, new DistributedCacheEntryOptions()
- {
- AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120) // 过期时间
- });
- }
- base.ViewBag.RedisCacheNow = time;
- }
- #endregion
-》运行效果, Redis 缓存在多个客户端中也将不会改变.
5, 自定义缓存 - CustomCache
我们来进行一次重复造轮子, 实现类似内存缓存 - MemoryCache 的效果. 首先我们定义自定义接口 - ICustomCache, 然后实现自定义缓存 CustomCache.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace ShiQuan.WebTest.Helpers
- {
- /// <summary>
- /// 自定义缓存接口
- /// </summary>
- public interface ICustomCache
- {
- void Add(string key, object value);
- T Get<T>(string key);
- bool Exists(string key);
- void Remove(string key);
- }
- /// <summary>
- /// 自定义缓存
- /// </summary>
- public class CustomCache:ICustomCache
- {
- private readonly Dictionary<string, object> keyValues = new Dictionary<string, object>();
- /// <summary>
- /// 增加内容
- /// </summary>
- /// <param name="key"></param>
- /// <param name="value"></param>
- public void Add(string key,object value)
- {
- this.keyValues.Add(key, value);
- }
- /// <summary>
- /// 获取值
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="key"></param>
- /// <returns></returns>
- public T Get<T> (string key)
- {
- return (T)this.keyValues[key];
- }
- /// <summary>
- /// 判断是否存在
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public bool Exists(string key)
- {
- return this.keyValues.ContainsKey(key);
- }
- /// <summary>
- /// 移除值
- /// </summary>
- /// <param name="key"></param>
- public void Remove(string key)
- {
- this.keyValues.Remove(key);
- }
- }
- }
-》项目注册接口及实现
- /* 增加自定义缓存 */
- //services.AddTransient<ICustomCache, CustomCache>();// 进程实例模式
- services.AddSingleton<ICustomCache, CustomCache>(); // 程序单例模式
-》控制器调用自定义缓存, 实现内容保存与读取, 在页面中显示.
- #region 自定义缓存
- {
- var time = string.Empty;
- if (this._iCustomCache.Exists(key) == false)
- {
- time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff");
- this._iCustomCache.Add(key, time);
- }
- time = this._iCustomCache.Get<String>(key);
- base.ViewBag.CustomCacheNow = time;
- }
- #endregion
从运行的效果, 我们可以看到, 达到类似内存缓存 MemoryCache 的效果.
至此,.net core 跨平台开发服务器缓存开发实战介绍完毕, 有不当地方, 欢迎指正!
来源: https://www.cnblogs.com/henxiao25/p/12644168.html