• .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 目录及文件到debugin 目录。

       

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

  • 相关阅读:
    code vs 1029 遍历问题 区间dp
    UVA 10891 Game of Sum 区间dp
    UVA 10635 Prince and Princess 最长公共子序列(nlongn)
    Codeforces Round #301 (Div. 2) D 概率DP
    LightOJ 1422 区间dp
    poj 1651 区间dp
    使用log4net+IExceptionFilter+Server酱完成异常日志信息推送
    MVC基础之控制器常见返回类型
    .NET Core中的IoC和DI
    使用Layui前端框架完成简单的增删改查
  • 原文地址:https://www.cnblogs.com/henxiao25/p/12644168.html
Copyright © 2020-2023  润新知