分布式缓存能够处理大量的动态数据,因此比较适合应用在Web 2.0时代中的社交网站等需要由用户生成内容的场景。从本地缓存扩展到分布式缓存后,关注重点从CPU、内存、缓存之间的数据传输速度差异也扩展到了业务系统、数据库、分布式缓存之间的数据传输速度差异。

如图:

实现步骤

1.首先配置Redis,这里不做详细记录,自己百度安装

2.打开你的项目,在appsettings.json配置如下代码

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"Session_Timeout": "30",
"redis_connstr": {
"master_conn": "127.0.0.1:6379,password=root"
}
}

  

这里配置了session的时间和Redis的连接字符串

3.使用NuGet工具包,安装Microsoft.Extensions.Caching.Redis,具体操作不详细讲解

4.我们这里封装一个类ConfigHelper,用来读取appsettings.json,具体代码如下:

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks; namespace ProjectManage
{
public class ConfigHelper
{
private static IConfiguration _configuration; static ConfigHelper()
{
//在当前目录或者根目录中寻找appsettings.json文件
var fileName = "appsettings.json"; var directory = AppContext.BaseDirectory;
directory = directory.Replace("\\", "/"); var filePath = $"{directory}/{fileName}";
if (!File.Exists(filePath))
{
var length = directory.IndexOf("/bin");
filePath = $"{directory.Substring(0, length)}/{fileName}";
} var builder = new ConfigurationBuilder()
.AddJsonFile(filePath, false, true); _configuration = builder.Build();
} public static string GetSectionValue(string key)
{
return _configuration.GetSection(key).Value;
} public static IEnumerable<IConfigurationSection> GetChildrenValue(string key)
{
return _configuration.GetSection(key).GetChildren();
}
}
}

  

5.打开Startup.cs文件,导入命名空间using Microsoft.Extensions.DependencyInjection.Extensions,在ConfigureServices方法中写入以下内容:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDistributedRedisCache(option =>
{
//redis 数据库连接字符串
option.Configuration = ConfigHelper.GetSectionValue("redis_connstr:master_conn");
//redis 实例名
option.InstanceName = "Test"; });
//注入Session模块
services.AddSession(option =>
{
option.IdleTimeout = TimeSpan.FromMinutes(Convert.ToDouble(ConfigHelper.GetSectionValue("Session_Timeout")));
});
//注入Session调用模块
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

  

6.在Configure方法中配置如下:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
} app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();//增加
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
      }

  

7.使用session前导入命名空间using Microsoft.AspNetCore.Http,使用如下代码:

   public IActionResult Index()
{
HttpContext.Session.SetString("sa", "123");
return View();
} public IActionResult About()
{
var sa= HttpContext.Session.GetString("sa");
ViewData["Message"] = "Your application description page."; return View();
}

  

8.使用redis客户端可以看到你所存的session的值,如图所示

以上就是全部的实现步骤

.NetCore实现简单的分布式缓存的更多相关文章

  1. Golang校招简历项目-简单的分布式缓存

    前言 前段时间,校招投了golang岗位,但是没什么好的项目往简历上写,于是参考了许多网上资料,做了一个简单的分布式缓存项目. 现在闲下来了,打算整理下. github项目地址:https://git ...

  2. 我发起了一个 .Net Core 平台上的 分布式缓存 开源项目 ShareMemory 用于 取代 Redis

    Redis 的 安装 是 复杂 的, 使用 是 复杂 的, Redis 的 功能 是 重型 的, Redis 本身的 技术实现 是 复杂 的 . Redis 是用 C 写的, C 语言 编写的代码需要 ...

  3. CYQ.Data 对于分布式缓存Redis、MemCache高可用的改进及性能测试

    背景: 随着.NET Core 在 Linux 下的热动,相信动不动就要分布式或集群的应用的需求,会慢慢火起来. 所以这段时间一直在研究和思考分布式集群的问题,同时也在思考把几个框架的思维相对提升到这 ...

  4. c#实例化继承类,必须对被继承类的程序集做引用 .net core Redis分布式缓存客户端实现逻辑分析及示例demo 数据库笔记之索引和事务 centos 7下安装python 3.6笔记 你大波哥~ C#开源框架(转载) JSON C# Class Generator ---由json字符串生成C#实体类的工具

    c#实例化继承类,必须对被继承类的程序集做引用   0x00 问题 类型“Model.NewModel”在未被引用的程序集中定义.必须添加对程序集“Model, Version=1.0.0.0, Cu ...

  5. Distributed Cache(分布式缓存)-SqlServer

    分布式缓存是由多个应用服务器共享的缓存,通常作为外部服务存储在单个应用服务器上,常用的有SqlServer,Redis,NCache. 分布式缓存可以提高ASP.NET Core应用程序的性能和可伸缩 ...

  6. CRL快速开发框架系列教程六(分布式缓存解决方案)

    本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...

  7. ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存

    ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存 part 1:给我点时间,允许我感慨一下2016年 正好有时间,总结一下最近使用的一些技术,也算是为2016年画上一个完 ...

  8. CYQ.Data V5 分布式缓存Redis应用开发及实现算法原理介绍

    前言: 自从CYQ.Data框架出了数据库读写分离.分布式缓存MemCache.自动缓存等大功能之后,就进入了频繁的细节打磨优化阶段. 从以下的更新列表就可以看出来了,3个月更新了100条次功能: 3 ...

  9. CYQ.Data V5 分布式缓存MemCached应用开发介绍

    前言 今天大伙还在热议关于.NET Core的东西,我只想说一句:在.NET 跨平台叫了这么多年间,其实人们期待的是一个知名的跨平台案例,而不是一堆能跨平台的消息. 好,回头说说框架: 在框架完成数据 ...

随机推荐

  1. 【Dubbo 源码解析】04_Dubbo 服务注册&暴露

    Dubbo 服务注册&暴露 Dubbo 服务暴露过程是通过 com.alibaba.dubbo.config.spring.ServiceBean 来实现的.Spring 容器 refresh ...

  2. LeetCode 51 N-Queens II

    Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe ...

  3. java数值比较

    import org.junit.Test; public class NumberCompare { /** * 数值比较,以Float为例 */ @Test public void testNam ...

  4. 【sql基础】按照名字分组查询时间最早的一条记录

    给出2种解决方案 rownumber SELECT * FROM ( SELECT IdentityID, OpenID, ROW_NUMBER() OVER(PARTITION BY OpenID ...

  5. GO语言-基础语法:条件判断

    1. IF判断(aa.txt内容:asdfgh.bb.txt内容:12345) package main import ( "io/ioutil" "fmt" ...

  6. 进程池的同步与异步用法Pool

    进程池的同步,如下程序: from multiprocessing import Pool import time import os def func(n): print('start 进程 %s' ...

  7. css处理文本溢出

    css: .box{ width: 100px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; } white-space: ...

  8. ruby 基础知识 - Class 与 Module

    原文 1. 因為 Ruby 並沒有「屬性」(property/attribute)這樣的設計,要取用實體變數,需要另外定義的方法才行: class Cat def initialize(name, g ...

  9. eclipse安装反编译decompiler方式一

    (转发位置:https://www.cnblogs.com/zs-notes/p/8991503.html) eclipse安装JD-eclipse反编译插件 1.在eclipse的help中选择In ...

  10. eclipse中的快捷键的使用