【发布时间】:2017-11-01 23:42:25
【问题描述】:
我们正面临 Redis 缓存问题,它导致我们的网站崩溃。
以下是我们的实现方式:
我们使用了以下连接字符串:
"*******.redis.cache.windows.net:6380,password=*****=,ssl=True,abortConnect=False"
我们创建了一个服务类:
using Microsoft.Extensions.Options;
using SarahahDataAccessLayer;
using StackExchange.Redis;
using System;
namespace Sarahah.Services
{
public class RedisService
{
private static Lazy<ConnectionMultiplexer> lazyConnection;
private readonly ApplicationSettings _settings;
public RedisService(IOptions<ApplicationSettings> settings)
{
_settings = settings.Value;
lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
return ConnectionMultiplexer.Connect(_settings.RedisConnection);
});
}
public ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
}
}
然后在 Startup.cs 我使用以下内容:
services.AddSingleton<RedisService>();
然后在控制器中我们使用依赖注入并分配给多路复用器:
connectionMultiplexer = redisService.Connection;
这是我们从缓存中获取的方式:
private async Task<string> GetFromCache(string key)
{
if (connectionMultiplexer.IsConnected)
{
var cache = connectionMultiplexer.GetDatabase();
return await cache.StringGetAsync(key);
}
else
{
return null;
}
}
这就是我们删除的方式:
private async Task DeleteFromCache(string subdomain)
{
if (connectionMultiplexer.IsConnected)
{
var cache = connectionMultiplexer.GetDatabase();
await cache.KeyDeleteAsync(subdomain).ConfigureAwait(false);
}
}
这就是我们添加的方式:
{
if (connectionMultiplexer.IsConnected)
{
var cache = connectionMultiplexer.GetDatabase();
TimeSpan expiresIn;
// Search Cache
if (key.Contains("-"))
{
expiresIn = new TimeSpan(0, GetMessagesCacheExpiryMinutes, 0);
}
// User info cache
else
{
expiresIn = new TimeSpan(GetProfileCacheExpiryHours, 0, 0);
}
await cache.StringSetAsync(key, serializedData, expiresIn).ConfigureAwait(false);
}
但是,我们收到以下错误: 没有可用于服务此操作的连接
虽然我们有很多用户,但我们在 Azure 门户中只看到很少的连接:
请注意,我们将 redis 缓存托管在网络应用的同一区域。
感谢您的支持。
【问题讨论】:
标签: asp.net azure caching redis asp.net-core