ASP.NET 核心中的 Redis 缓存
Redis Cache in ASP.NET Core
我是 Redis 新手,使用 VS 2015 和 ASP.NET 核心应用程序 (v 1.0),我安装了 nugget 包:
Install-Package StackExchange.Redis
但是我无法将它注入和配置到我的服务中,没有 RedisCache 或“AddDistributedRedisCache”方法。
如何注入使用?
01.Download 来自 download 的最新 redis,安装并启动来自 services.msc
的 redis 服务
02.Add project.json
中的两个库
"Microsoft.Extensions.Caching.Redis.Core": "1.0.3",
"Microsoft.AspNetCore.Session": "1.1.0",
03.Add 你在
中进行了依赖注入
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
//For Redis
services.AddSession();
services.AddDistributedRedisCache(options =>
{
options.InstanceName = "Sample";
options.Configuration = "localhost";
});
}
并在 Configure
方法中添加 app.UseMvc 行的顶部
app.UseSession();
在asp.net核心的会话存储中使用redis。现在你可以在HomeController.cs
中这样使用
public class HomeController : Controller
{
private readonly IDistributedCache _distributedCache;
public HomeController(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
//Use version Redis 3.22
//
public IActionResult Index()
{
_distributedCache.SetString("helloFromRedis", "world");
var valueFromRedis = _distributedCache.GetString("helloFromRedis");
return View();
}
}
我使用了以下解决方案并得到了答案。
1.Download Redis-x64-3.0.504.msi
并安装它 (link)
2.Install Microsoft.Extensions.Caching.StackExchangeRedis
来自 Nuget 包管理器
3.Inside Startup.cs class ,在ConfigureServices方法中,添加这条命令:
services.AddStackExchangeRedisCache(options => options.Configuration = "localhost:6379");
将 IDistributedCache 注入控制器:
private readonly IDistributedCache _distributedCache;
public WeatherForecastController( IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
5.In结束:
[HttpGet]
public async Task<List<string>> GetStringItems()
{
string cacheKey = "redisCacheKey";
string serializedStringItems;
List<string> stringItemsList;
var encodedStringItems = await _distributedCache.GetAsync(cacheKey);
if (encodedStringItems != null)
{
serializedStringItems = Encoding.UTF8.GetString(encodedStringItems);
stringItemsList = JsonConvert.DeserializeObject<List<string>>(serializedStringItems);
}
else
{
stringItemsList = new List<string>() { "John wick", "La La Land", "It" };
serializedStringItems = JsonConvert.SerializeObject(stringItemsList);
encodedStringItems = Encoding.UTF8.GetBytes(serializedStringItems);
var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(1))
.SetAbsoluteExpiration(TimeSpan.FromHours(6));
await _distributedCache.SetAsync(cacheKey, encodedStringItems, options);
}
return stringItemsList;
}
祝你好运!!!
Install-Package StackExchange.Redis
Redis 服务:
public class RedisService : IDisposable
{
private readonly IConnectionMultiplexer Connection;
private readonly string _connectionString;
public RedisService(IConfiguration Configuration, ILogger<RedisService> logger)
{
_connectionString = Configuration.GetConnectionString("redis connection string");
var conn = new Lazy<IConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_connectionString));
Connection = conn.Value;
Main = Connection.GetDatabase(1);
logger.LogWarning("Redis Service Attached!");
}
public IDatabase Main { get; }
public void Dispose()
{
Connection?.Dispose();
}
}
在startup.cs
中添加服务
services.AddSingleton<RedisService>();
现在在您的控制器中使用它
我是 Redis 新手,使用 VS 2015 和 ASP.NET 核心应用程序 (v 1.0),我安装了 nugget 包:
Install-Package StackExchange.Redis
但是我无法将它注入和配置到我的服务中,没有 RedisCache 或“AddDistributedRedisCache”方法。
如何注入使用?
01.Download 来自 download 的最新 redis,安装并启动来自 services.msc
的 redis 服务02.Add project.json
中的两个库"Microsoft.Extensions.Caching.Redis.Core": "1.0.3",
"Microsoft.AspNetCore.Session": "1.1.0",
03.Add 你在
中进行了依赖注入public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
//For Redis
services.AddSession();
services.AddDistributedRedisCache(options =>
{
options.InstanceName = "Sample";
options.Configuration = "localhost";
});
}
并在
Configure
方法中添加 app.UseMvc 行的顶部app.UseSession();
在asp.net核心的会话存储中使用redis。现在你可以在HomeController.cs
中这样使用public class HomeController : Controller
{
private readonly IDistributedCache _distributedCache;
public HomeController(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
//Use version Redis 3.22
//
public IActionResult Index()
{
_distributedCache.SetString("helloFromRedis", "world");
var valueFromRedis = _distributedCache.GetString("helloFromRedis");
return View();
}
}
我使用了以下解决方案并得到了答案。
1.Download Redis-x64-3.0.504.msi 并安装它 (link)
2.Install Microsoft.Extensions.Caching.StackExchangeRedis
来自 Nuget 包管理器
3.Inside Startup.cs class ,在ConfigureServices方法中,添加这条命令:
services.AddStackExchangeRedisCache(options => options.Configuration = "localhost:6379");
将 IDistributedCache 注入控制器:
private readonly IDistributedCache _distributedCache; public WeatherForecastController( IDistributedCache distributedCache) { _distributedCache = distributedCache; }
5.In结束:
[HttpGet]
public async Task<List<string>> GetStringItems()
{
string cacheKey = "redisCacheKey";
string serializedStringItems;
List<string> stringItemsList;
var encodedStringItems = await _distributedCache.GetAsync(cacheKey);
if (encodedStringItems != null)
{
serializedStringItems = Encoding.UTF8.GetString(encodedStringItems);
stringItemsList = JsonConvert.DeserializeObject<List<string>>(serializedStringItems);
}
else
{
stringItemsList = new List<string>() { "John wick", "La La Land", "It" };
serializedStringItems = JsonConvert.SerializeObject(stringItemsList);
encodedStringItems = Encoding.UTF8.GetBytes(serializedStringItems);
var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(1))
.SetAbsoluteExpiration(TimeSpan.FromHours(6));
await _distributedCache.SetAsync(cacheKey, encodedStringItems, options);
}
return stringItemsList;
}
祝你好运!!!
Install-Package StackExchange.Redis
Redis 服务:
public class RedisService : IDisposable
{
private readonly IConnectionMultiplexer Connection;
private readonly string _connectionString;
public RedisService(IConfiguration Configuration, ILogger<RedisService> logger)
{
_connectionString = Configuration.GetConnectionString("redis connection string");
var conn = new Lazy<IConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_connectionString));
Connection = conn.Value;
Main = Connection.GetDatabase(1);
logger.LogWarning("Redis Service Attached!");
}
public IDatabase Main { get; }
public void Dispose()
{
Connection?.Dispose();
}
}
在startup.cs
中添加服务services.AddSingleton<RedisService>();
现在在您的控制器中使用它