asp.net core上使用Redis探索(2)
在<<asp.net core上使用Redis探索(1)>>中,我介绍了一个微软官方实现Microsoft.Extensions.Caching.Redis的类库,这次,我们使用微软官方的Redis客户端。
使用Nuget引入Microsoft.Extensions.Caching.Redis库, 依赖项:
Microsoft.Extensions.Caching.Abstract
Microsoft.Extensions.Options
StackExchange.Redis.StrongName
原来Microsoft.Extensions.Caching.Redis其实就是封装了StackExchange.redis,作为.net core平台下的redis客户端与redis通信的。
源码地址:
https://github.com/aspnet/Caching/tree/dev/src/Microsoft.Extensions.Caching.Redis
源码分析:
RedisCache继承自IDistributeCache接口,该接口是Microsoft.Extensions.Caching.Distributed命名空间下的一个接口,主要就是封装了Redis的一些最基本的操作,比如,Set, Get, Refresh, Remove.就是最基本的增删改查。
RedisCache类中有一个用于同步的SemaphoreSlim类,该类是CLR中的同步遍历的混合构造——内核模式和用户模式的混合。该类除了显式实现了IDistributedCache的所有方法外,还有一个重要的方法要说下,那就是Connect()方法:
private void Connect()
{
if (_cache != null)
{
return;
} _connectionLock.Wait();
try
{
if (_cache == null)
{
_connection = ConnectionMultiplexer.Connect(_options.Configuration);
_cache = _connection.GetDatabase();
}
}
finally
{
_connectionLock.Release();
}
}
该方法用于连接Redis服务器,通过RedisCacheOptions这个类的属性,来连接redis数据库,源码:
/// <summary>
/// Configuration options for <see cref="RedisCache"/>.
/// </summary>
public class RedisCacheOptions : IOptions<RedisCacheOptions>
{
/// <summary>
/// The configuration used to connect to Redis.
/// </summary>
public string Configuration { get; set; } /// <summary>
/// The Redis instance name.
/// </summary>
public string InstanceName { get; set; } RedisCacheOptions IOptions<RedisCacheOptions>.Value
{
get { return this; }
}
}
其中的Configuration属性就是我们的一般在.config文件中配置redis连接语句的地方,随后我们会讲到应用。而InstanceName是什么?继续看源码(RedisCache.cs文件):
private readonly RedisCacheOptions _options;
public RedisCache(IOptions<RedisCacheOptions> optionsAccessor)
{
if (optionsAccessor == null)
{
throw new ArgumentNullException(nameof(optionsAccessor));
} _options = optionsAccessor.Value; // This allows partitioning a single backend cache for use with multiple apps/services.
_instance = _options.InstanceName ?? string.Empty;
}
可以看到,这个属性是可以设置为空的,那么它到底是什么呢?这个就是我们在存储redis的时候的前缀了,我们可以这么这是Demo, 或者Demo:test等。
也就是说RedisCache类主要就是实现了IDistributedCache接口的所有方法,同时另外实现了Connect()方法用来连接redis,而这个的连接又是基于StackExchange.Redis(关于StackExchange.Redis请看 StackExchange.Redis通用封装类分享 )的ConnectionMultiplexer。但是我们在大型项目中使用的redis队列在RedisCache类中并没有实现,但是,要知道整个asp.net-core都是可拓展的,我们可以基于RedisCache类再实现一个pub/sub方法用来做消息队列。
最后使用asp.net-core默认的DI容器将RedisCache类注册到框架中。RedisCacheServiceCollectionExtensions类源码:
/// <summary>
/// Extension methods for setting up Redis distributed cache related services in an <see cref="IServiceCollection" />.
/// </summary>
public static class RedisCacheServiceCollectionExtensions
{
/// <summary>
/// Adds Redis distributed caching services to the specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="setupAction">An <see cref="Action{RedisCacheOptions}"/> to configure the provided
/// <see cref="RedisCacheOptions"/>.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddDistributedRedisCache(this IServiceCollection services, Action<RedisCacheOptions> setupAction)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
} if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
} services.AddOptions();
services.Configure(setupAction);
// .net core DI容器的使用无非就是在容器中实例化接口,而接口的的实例化,是通过实例化接口的派生类(即以接口为父类的子类)...
services.Add(ServiceDescriptor.Singleton<IDistributedCache, RedisCache>()); return services;
}
}
在这里我们基于IServiceCollection接口拓展出来了一个方法,该方法就是微软官方为我们创建的基于Redis的实现了,在最后使用DI的三种方法的Singleton来实现IOC。那么我们怎么来使用呢?
引入完了Microsoft.Extensions.Caching.Redis之后,在Startup类中:
services.AddDistributedRedisCache(option =>
{
option.Configuration = "123.207.96.138:6379, password=*****";
option.InstanceName = "";
});
个人的建议是给Redis设置一个密码,要不然容易被攻击。
接下来就是给Redis设置值了, 我们新建一个WebApi的程序,然后新建一个HomeController Api控制器
[Produces("application/json")]
[Route("api/[controller]")]
public class HomeController : Controller
{
// 通过构造函数注入,内置IOC容器实例化了之后,就可以通过接口对象来调用相应的函数了.
private readonly IDistributedCache _distributedCache;
public HomeController(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
[HttpGet]
public async Task<string> Get()
{
var cacheKey = "TheTime";
//await _distributedCache.RemoveAsync(cacheKey);
var existingTime = _distributedCache.GetString(cacheKey);
if (!string.IsNullOrEmpty(existingTime))
{
return "Fetched from cache : " + existingTime;
}
else
{
existingTime = DateTime.UtcNow.ToString();
_distributedCache.SetString(cacheKey, existingTime);
return "Added to cache : " + existingTime;
}
}
}
代码我就不运行了,亲测能用。
百度云盘demo下载地址:
链接:https://pan.baidu.com/s/1vzuS5pEk_Ouh9I-NkPWXfg 密码:armw
asp.net core上使用Redis探索(2)的更多相关文章
- 使用Code First建模自引用关系笔记 asp.net core上使用redis探索(1) asp.net mvc控制器激活全分析 语言入门必学的基础知识你还记得么? 反射
使用Code First建模自引用关系笔记 原文链接 一.Has方法: A.HasRequired(a => a.B); HasOptional:前者包含后者一个实例或者为null HasR ...
- asp.net core 上使用redis探索(3)--redis示例demo
由于是基于.net-core平台,所以,我们最好是基于IDistributedCache接口来实现.ASP.NET-CORE下的官方redis客户端实现是基于StackExchange的.但是官方提供 ...
- asp.net core上使用redis探索(1)
基于Ubuntu安装redis, 我找的一个很好的网站: https://www.digitalocean.com/community/tutorials/how-to-install-and-con ...
- asp.net core上使用Redis demo
整体思路:(1.面向接口编程 2.Redis可视化操作IDE 3.Redis服务) [无私分享:ASP.NET CORE 项目实战(第十一章)]Asp.net Core 缓存 MemoryCache ...
- asp.net core 实战之 redis 负载均衡和"高可用"实现
1.概述 分布式系统缓存已经变得不可或缺,本文主要阐述如何实现redis主从复制集群的负载均衡,以及 redis的"高可用"实现, 呵呵双引号的"高可用"并不是 ...
- Asp.Net Core Web应用程序—探索
前言 作为一个Windows系统下的开发者,我对于Core的使用机会几乎为0,但是考虑到微软的战略规划,我觉得,Core还是有先了解起来的必要. 因为,目前微软已经搞出了两个框架了,一个是Net标准( ...
- ASP.NET Core WebApi基于Redis实现Token接口安全认证
一.课程介绍 明人不说暗话,跟着阿笨一起玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性.那么对于我们来说,如何确保数据的安全将会是需要思考的问题.在ASP.NET WebSer ...
- 在ASP.NET Core上实施每个租户策略的数据库
在ASP.NET Core上实施每个租户策略的数据库 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://g ...
- Angular 2的HTML5 pushState在ASP.NET Core上的解决思路
Angular 2的HTML5 pushState在ASP.NET Core上的解决思路 正如Angular 2在Routing & Navigation中所提及的那样,Angular 2是推 ...
随机推荐
- C语言函数--atoi
在Java语言中,由于面向对象的思想,它对基本数据类型也进行了相应的封装,例如 int 就封装成了 Integer 类,这无疑会使我们的操作方便了许多,例如,有一个字符串,我想把它转换为i ...
- [python] 带有参数并且传递参数的装饰器
场景时这样的,我有个一大堆任务,我要给这些任务计时,入库.就需要一个带有参数的装饰器来记录任务名称, 在任务执行前和执行之后都需要记录任务当时执行的时刻. #-*- encoding=utf-8 -* ...
- Android开发学习之路--UI之简单聊天界面
学了很多的ui的知识,这里就来实现个聊天的界面,首先来实现个layout的xml,代码如下: <?xml version="1.0" encoding="utf-8 ...
- xml的今生今世
跟随小编学习的脚步,今天小编来简单总结一下xml的今生今世,xml百度百科对她这样诠释到:可扩展标记语言 (ExtensibleMarkup Language, XML),用于标记电子文件使其具有结构 ...
- 简单模拟 Spring
简单的理解Spring的实现过程,模拟了Spring的读取配置文件 项目结构
- 谈谈Ext JS的组件——布局的使用方法续二
绝对布局(Ext.layout.container.Absolute) 绝对布局让我回想到了使用Foxpro开发的时候,哪时候的界面布局就是这样,通过设置控件的左上角坐标(x,y)和宽度来进行的,因为 ...
- 详解ebs接口之客户配置文件导入(二)
------------------------------------ -- 1a. Setup the Org_id ------------------------------------ ex ...
- 《java入门第一季》之面向对象接口面试题
首先,(1)叙述接口的成员特点: /* 接口成员特点 成员变量:只能是常量,默认都是常量,并且是静态的. 默认修饰符:public static final 建议:自己手动给出类似:public st ...
- linux进程管理之进程创建
所谓进程就是程序执行时的一个实例. 它是现代操作系统中一个很重要的抽象,我们从进程的生命周期:创建,执行,消亡来分析一下Linux上的进程管理实现. 一:前言 进程管理结构; 在内核中,每一个进程对应 ...
- DrawerLayout实现网易新闻抽屉效果
个人感觉网易的客户端比较前卫,有很多新鲜的东西,有时候模仿这些好的客户端能学到很多东西 开始今天的主要课题,下面是网易客户端抽屉模式实现的效果 其实有个Drawerlayout这个布局,你得问题就已经 ...