惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

罗磊的独立博客
www.infosecurity-magazine.com
www.infosecurity-magazine.com
V
Visual Studio Blog
T
The Blog of Author Tim Ferriss
GbyAI
GbyAI
Y
Y Combinator Blog
雷峰网
雷峰网
Last Week in AI
Last Week in AI
Jina AI
Jina AI
月光博客
月光博客
G
Google Developers Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
博客园 - 三生石上(FineUI控件)
Hacker News - Newest:
Hacker News - Newest: "LLM"
N
News | PayPal Newsroom
H
Heimdal Security Blog
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
AWS News Blog
AWS News Blog
NISL@THU
NISL@THU
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
P
Privacy International News Feed
I
Intezer
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
L
LINUX DO - 最新话题
S
Schneier on Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
小众软件
小众软件
博客园 - 聂微东
V2EX - 技术
V2EX - 技术
W
WeLiveSecurity
Security Latest
Security Latest
PCI Perspectives
PCI Perspectives
The Hacker News
The Hacker News
T
Threatpost
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Latest news
Latest news
L
LINUX DO - 热门话题
J
Java Code Geeks
A
Arctic Wolf
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Troy Hunt's Blog

博客园 - 衡斅

基于.net C# Socket WinForm MQTT 客户端开发 基于.Net C# 通信开发-网络调试助手 基于.Net C# 通信开发-串口调试助手 基于HBuilderX+UniApp+ColorUi+UniCloud 优宝库 开发实战(一) .net core 跨平台开发 微服务架构 基于Nginx反向代理 服务集群负载均衡 redis 分布式缓存实战-redis 事务 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(4)-Excel文件读、写操作 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(3)-项目依赖注入 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(2)-业务项目搭建 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(1)-Web前端页面 基于html5 plus + Mui 移动App开发(三)-食全库 基于Html5 Plus + Vue + Mui 移动App开发(三)-文件操作(读取、保存、更新数据) 基于Html5 Plus + Vue + Mui 移动App 开发(二) 基于html5 plus + Mui 移动App开发(一) 基于百度地图的产品销售的单位查看功能设计与实现 实全软件产品自动升级管理解决方案 基于服务(Web Service)的文件管理Winform客户端实现(二) 如何通过WPS 2013 API 将Office(Word、Excel和PPT)文件转PDF文件 如何通过SerialPort读取和写入设备COM端口数据
.Net Core 跨平台开发实战-服务器缓存:本地缓存、分布式缓存、自定义缓存
衡斅 · 2020-04-06 · via 博客园 - 衡斅

.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(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 跨平台开发服务器缓存开发实战介绍完毕,有不当地方,欢迎指正!