环境:ASP.NET Core MVC,Redis-Win-x64-3.2.100
本文介绍在ASP.NET Core MVC中怎么用Redis缓存数据。
1、启动Redis服务器,就是让我们的Redis跑起来,具体参照https://blog.csdn.net/u012835032/article/details/115438693。
2、要在ASP.NET Core MVC中用Redis需要做什么?参考https://blog.csdn.net/u012835032/article/details/115443710。
代码很简单,但开始前需要先了解两个要用到对象
DistributedCacheExtensions:包括对缓存操作的方法
#region 程序集 Microsoft.Extensions.Caching.Abstractions, Version=2.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Extensions.Caching.Distributed
{
//
// 摘要:
// Extension methods for setting data in an Microsoft.Extensions.Caching.Distributed.IDistributedCache.
public static class DistributedCacheExtensions
{
//
// 摘要:
// Gets a string from the specified cache with the specified key.
//
// 参数:
// cache:
// The cache in which to store the data.
//
// key:
// The key to get the stored data for.
//
// 返回结果:
// The string value from the stored cache key.
public static string GetString(this IDistributedCache cache, string key);
//
// 摘要:
// Asynchronously gets a string from the specified cache with the specified key.
//
// 参数:
// cache:
// The cache in which to store the data.
//
// key:
// The key to get the stored data for.
//
// token:
// Optional. A System.Threading.CancellationToken to cancel the operation.
//
// 返回结果:
// A task that gets the string value from the stored cache key.
[AsyncStateMachine(typeof(<GetStringAsync>d__7))]
public static Task<string> GetStringAsync(this IDistributedCache cache, string key, CancellationToken token = default(CancellationToken));
//
// 摘要:
// Sets a sequence of bytes in the specified cache with the specified key.
//
// 参数:
// cache:
// The cache in which to store the data.
//
// key:
// The key to store the data in.
//
// value:
// The data to store in the cache.
//
// 异常:
// T:System.ArgumentNullException:
// Thrown when key or value is null.
public static void Set(this IDistributedCache cache, string key, byte[] value);
//
// 摘要:
// Asynchronously sets a sequence of bytes in the specified cache with the specified
// key.
//
// 参数:
// cache:
// The cache in which to store the data.
//
// key:
// The key to store the data in.
//
// value:
// The data to store in the cache.
//
// token:
// Optional. A System.Threading.CancellationToken to cancel the operation.
//
// 返回结果:
// A task that represents the asynchronous set operation.
//
// 异常:
// T:System.ArgumentNullException:
// Thrown when key or value is null.
public static Task SetAsync(this IDistributedCache cache, string key, byte[] value, CancellationToken token = default(CancellationToken));
//
// 摘要:
// Sets a string in the specified cache with the specified key.
//
// 参数:
// cache:
// The cache in which to store the data.
//
// key:
// The key to store the data in.
//
// value:
// The data to store in the cache.
//
// 异常:
// T:System.ArgumentNullException:
// Thrown when key or value is null.
public static void SetString(this IDistributedCache cache, string key, string value);
//
// 摘要:
// Sets a string in the specified cache with the specified key.
//
// 参数:
// cache:
// The cache in which to store the data.
//
// key:
// The key to store the data in.
//
// value:
// The data to store in the cache.
//
// options:
// The cache options for the entry.
//
// 异常:
// T:System.ArgumentNullException:
// Thrown when key or value is null.
public static void SetString(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options);
//
// 摘要:
// Asynchronously sets a string in the specified cache with the specified key.
//
// 参数:
// cache:
// The cache in which to store the data.
//
// key:
// The key to store the data in.
//
// value:
// The data to store in the cache.
//
// token:
// Optional. A System.Threading.CancellationToken to cancel the operation.
//
// 返回结果:
// A task that represents the asynchronous set operation.
//
// 异常:
// T:System.ArgumentNullException:
// Thrown when key or value is null.
public static Task SetStringAsync(this IDistributedCache cache, string key, string value, CancellationToken token = default(CancellationToken));
//
// 摘要:
// Asynchronously sets a string in the specified cache with the specified key.
//
// 参数:
// cache:
// The cache in which to store the data.
//
// key:
// The key to store the data in.
//
// value:
// The data to store in the cache.
//
// options:
// The cache options for the entry.
//
// token:
// Optional. A System.Threading.CancellationToken to cancel the operation.
//
// 返回结果:
// A task that represents the asynchronous set operation.
//
// 异常:
// T:System.ArgumentNullException:
// Thrown when key or value is null.
public static Task SetStringAsync(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken));
}
}
DistributedCacheEntryOptions:设置缓存有效期
#region 程序集 Microsoft.Extensions.Caching.Abstractions, Version=2.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
using System;
namespace Microsoft.Extensions.Caching.Distributed
{
public class DistributedCacheEntryOptions
{
public DistributedCacheEntryOptions();
//
// 摘要:
// Gets or sets an absolute expiration date for the cache entry.
public DateTimeOffset? AbsoluteExpiration { get; set; }
//
// 摘要:
// Gets or sets an absolute expiration time, relative to now.
public TimeSpan? AbsoluteExpirationRelativeToNow { get; set; }
//
// 摘要:
// Gets or sets how long a cache entry can be inactive (e.g. not accessed) before
// it will be removed. This will not extend the entry lifetime beyond the absolute
// expiration (if set).
public TimeSpan? SlidingExpiration { get; set; }
}
}
使用要先在Startup.cs把分布式缓存(IDistributedCache)加进来,就是ASP.NET Core MVC的Ioc那套玩儿。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedRedisCache(options =>
{
options.Configuration = "127.0.0.1:6379";
options.InstanceName = "RedisTest";
});
//password
//services.AddDistributedRedisCache(options =>
//{
// options.Configuration = "127.0.0.1:6379,password=123456,defaultdatabase=1";
// options.InstanceName = "RedisTest_";
//});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
控制器代码如下,利用DistributedCacheExtensions提供的方法写入和获取数据。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
namespace RedisTest
{
public class HomeController : BaseController
{
private IDistributedCache DistributedCache;
public HomeController(IDistributedCache distributedCache)
{
DistributedCache = distributedCache;
}
public IActionResult Index()
{
ViewBag.DistributedCacheDateTime = GetCacheDateTime();
return View();
}
private string GetCacheDateTime()
{
string dCacheKey = "Home-GetCacheDateTime";
//获取缓存数据
string data = DistributedCache.GetString(dCacheKey);
if (string.IsNullOrWhiteSpace(data))
{
data = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff");
//写入缓存,并指定缓存到期时间 300秒
DistributedCache.SetString(dCacheKey, data, new DistributedCacheEntryOptions()
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300)
});
}
return data;
}
}
}
可以在命令行通过keys命令看一下