.Net Core 跨平台开发实战-服务器缓存:本地缓存、分布式缓存、自定义缓存
.Net Core 跨平台开发实战-服务器缓存:本地缓存、分布式缓存、自定义缓存
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() //过期时间
});
}
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 跨平台开发服务器缓存开发实战介绍完毕,有不当地方,欢迎指正!
.Net Core 跨平台开发实战-服务器缓存:本地缓存、分布式缓存、自定义缓存的更多相关文章
- 《ASP.NET Core跨平台开发从入门到实战》Web API自定义格式化protobuf
<ASP.NET Core跨平台开发从入门到实战>样章节 Web API自定义格式化protobuf. 样章 Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于 ...
- [.net 面向对象程序设计深入](9).NET Core 跨平台开发环境搭建
[.net 面向对象程序设计深入](9).NET Core 跨平台开发环境搭建 1.概述 读前必备:认识.NET Core 上篇介绍了.NET 新的生态环境:包括.NET Framework..NET ...
- Visual Studio跨平台开发实战(5) - Xamarin Android多页面应用程式开发
原文 Visual Studio跨平台开发实战(5) - Xamarin Android多页面应用程式开发 前言 大部份的Android 都具有实体或虚拟的Back键. 因此在处理多页面应用程式时 ...
- Visual Studio跨平台开发实战(4) - Xamarin Android基本控制项介绍
原文 Visual Studio跨平台开发实战(4) - Xamarin Android基本控制项介绍 前言 不同于iOS,Xamarin 在Visual Studio中针对Android,可以直接设 ...
- Visual Studio跨平台开发实战(3) - Xamarin iOS多页面应用程式开发
原文 Visual Studio跨平台开发实战(3) - Xamarin iOS多页面应用程式开发 前言 在前一篇教学中, 我们学会如何使用Visual Studio 搭配Xcode 进行iOS基本控 ...
- Visual Studio跨平台开发实战(2) - Xamarin.iOS基本控制项介绍
原文 Visual Studio跨平台开发实战(2) - Xamarin.iOS基本控制项介绍 前言 在上一篇文章中, 我们介绍了Xamarin 以及简单的HelloWorld范例, 这次我们针对iO ...
- Visual Studio跨平台开发实战(1) - Hello Xamarin!
原文 Visual Studio跨平台开发实战(1) - Hello Xamarin! 前言 应用程式发展的脚步, 从来没有停过. 从早期的Windows 应用程式, 到网路时代的web 应用程式, ...
- 《ASP.NET Core项目开发实战入门》带你走进ASP.NET Core开发
<ASP.NET Core项目开发实战入门>从基础到实际项目开发部署带你走进ASP.NET Core开发. ASP.NET Core项目开发实战入门是基于ASP.NET Core 3.1 ...
- asp.net core跨平台开发从入门到实战文摘
第1章 .NET Core 第2章 dotnet命令 第3章 VS Code安装及介绍 第4章 VS2015开发.NET Core 第5章 ASP.NET Core 第6章 EF Core 第7章 A ...
随机推荐
- 手摸手教你在vue-cli里面使用vuex,以及vuex简介
写在前面: 这篇文章是在vue-cli里面使用vuex的一个极简demo,附带一些vuex的简单介绍.有需要的朋友可以做一下参考,喜欢的可以点波赞,或者关注一下,希望可以帮到大家. 本文首发于我的个人 ...
- html+css布局类型
一.单列布局 1.代码如下 <!doctype html> <html> <head> <meta charset="utf-8"/> ...
- bootstrapValidator验证的remote中data属性里获取select一直是默认值
budgetEditionNo:{ message:'版本号输入不正确' , validators:{ notEmpty:{ message:'版本号不能为空,请填写' } , remote:{ ur ...
- 负margin在页面布局中的应用
关于负margin的原理建议大家看看这篇文章:http://www.cnblogs.com/2050/archive/2012/08/13/2636467.html#2457812 一. 左右列固定, ...
- 通过mockjs来制作假数据
需用用到的模块为express和mockjs //导入模块开启服务器模块 const express=require('express') //导入假数据模块 const mockjs=require ...
- 关于form表单:hover没有修改表单子元素样式
原来在写todolist的时候遇到的一个问题 是关于form表单的hover属性设置背景颜色 想要实现的效果如下: 但是一开始直接给form加hover选择器的时候是这样: 可以看到这样子直接加会使得 ...
- django 知识点小结
以下内容为用django写blog中的一些知识点,权当复习. 一.定义view 1.get_object_or_404()是用get()查询数据,如果不存在就直接返回404 参数: get_objec ...
- 结巴分词demo
#encoding=utf-8 from __future__ import unicode_literals import sys sys.path.append("../") ...
- 写于疫情期间的一个plantUML例子
@startuml 这几天的正经事 start repeat if(思维清晰) then (yes) :刷题; else (no) if(想写程序) then (yes) :调项目; else (no ...
- git 查看commit的提交记录
相关命令: git log 查看所有提交记录 git show 查看提交详情 示例: git log: git show: 查看指定commit的详情:git show commitId 查看某次c ...