在<<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)的更多相关文章

  1. 使用Code First建模自引用关系笔记 asp.net core上使用redis探索(1) asp.net mvc控制器激活全分析 语言入门必学的基础知识你还记得么? 反射

    使用Code First建模自引用关系笔记   原文链接 一.Has方法: A.HasRequired(a => a.B); HasOptional:前者包含后者一个实例或者为null HasR ...

  2. asp.net core 上使用redis探索(3)--redis示例demo

    由于是基于.net-core平台,所以,我们最好是基于IDistributedCache接口来实现.ASP.NET-CORE下的官方redis客户端实现是基于StackExchange的.但是官方提供 ...

  3. asp.net core上使用redis探索(1)

    基于Ubuntu安装redis, 我找的一个很好的网站: https://www.digitalocean.com/community/tutorials/how-to-install-and-con ...

  4. asp.net core上使用Redis demo

    整体思路:(1.面向接口编程 2.Redis可视化操作IDE 3.Redis服务) [无私分享:ASP.NET CORE 项目实战(第十一章)]Asp.net Core 缓存 MemoryCache ...

  5. asp.net core 实战之 redis 负载均衡和"高可用"实现

    1.概述 分布式系统缓存已经变得不可或缺,本文主要阐述如何实现redis主从复制集群的负载均衡,以及 redis的"高可用"实现, 呵呵双引号的"高可用"并不是 ...

  6. Asp.Net Core Web应用程序—探索

    前言 作为一个Windows系统下的开发者,我对于Core的使用机会几乎为0,但是考虑到微软的战略规划,我觉得,Core还是有先了解起来的必要. 因为,目前微软已经搞出了两个框架了,一个是Net标准( ...

  7. ASP.NET Core WebApi基于Redis实现Token接口安全认证

    一.课程介绍 明人不说暗话,跟着阿笨一起玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性.那么对于我们来说,如何确保数据的安全将会是需要思考的问题.在ASP.NET WebSer ...

  8. 在ASP.NET Core上实施每个租户策略的数据库

    在ASP.NET Core上实施每个租户策略的数据库 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://g ...

  9. Angular 2的HTML5 pushState在ASP.NET Core上的解决思路

    Angular 2的HTML5 pushState在ASP.NET Core上的解决思路 正如Angular 2在Routing & Navigation中所提及的那样,Angular 2是推 ...

随机推荐

  1. 1.2、Android Studio为新设备创建一个模块

    模块为你的应用的源码.资源文件和app level设置(比如AndroidManifest.xml)提供了一个容器.每个模块可以独立的构建.测试和调试. 通过使用模块,Android Studio可以 ...

  2. android之View绘制

    Android系统的视图结构的设计也采用了组合模式,即View作为所有图形的基类,Viewgroup对View继承扩展为视图容器类,由此就得到了视图部分的基本结构--树形结构 View定义了绘图的基本 ...

  3. parcel和parcelable

    Parcel 在英文中有两个意思,其一是名词,为包裹,小包的意思: 其二为动词,意为打包,扎包.邮寄快递中的包裹也用的是这个词.Android采用这个词来表示封装消息数据.这个是通过IBinder通信 ...

  4. SSH深度历险(一)深入浅出Hibernate架构(一)-------映射解析——七种映射关系

            ORM,全称是(Object Relational Mapping),即对象关系映射.ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现,这样开发人员就可以把对数据 ...

  5. Android Service详解

    service作为四大组件值得我们的更多的关注 在Android中,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务.例如,一个从service播放音乐的音乐播放器,应 ...

  6. Redis主从和HA配置

    1同步原理 摘自:http://www.cnblogs.com/stephen-liu74/archive/2012/03/30/2364717.html "下面的列表清楚的解释了Redis ...

  7. java设计模式---三种工厂模式

    工厂模式提供创建对象的接口. 工厂模式分为三类:简单工厂模式(Simple Factory), 工厂方法模式(Factory Method)和抽象工厂模式(Abstract Factory).GOF在 ...

  8. 【一天一道LeetCode】#121. Best Time to Buy and Sell Stock

    # 一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Say ...

  9. 控件之combox

    一. combox显示     首先combox有两个属性来存储数据:DisplayMember(显示成员),ValueMember(值成员) ,DisplayMember是我们在combox界面上看 ...

  10. 海量数据挖掘MMDS week5: 计算广告Computational Advertising

    http://blog.csdn.net/pipisorry/article/details/49428053 海量数据挖掘Mining Massive Datasets(MMDs) -Jure Le ...