Lui*_*cia 9 c# azure stackexchange.redis azure-redis-cache
我有以下代码用于从缓存中获取信息.我不知道我的应用程序是否打开了太多连接,或者只是这个错误是由于天蓝色redis缓存的瞬态故障造成的.
这是堆栈跟踪
[RedisConnectionException:没有可用于此操作的连接:GET UserProfileInformation|globaladmin@xx.onmicrosoft.com]
1 processor, ServerEndPoint server) in c:\TeamCity\buildAgent\work\3ae0647004edff78\StackExchange.Redis\StackExchange\Redis\ConnectionMultiplexer.cs:1922 StackExchange.Redis.RedisBase.ExecuteSync(Message message, ResultProcessorc:\ TeamCity\buildAgent\work中的StackExchange.Redis.ConnectionMultiplexer.ExecuteSyncImpl(消息消息,ResultProcessor 1处理器,ServerEndPoint服务器)\3ae0647004edff78\StackExchange.Redis\StackExchange\Redis\RedisBase.cs:80 StackExchange.Redis.RedisDatabase.StringGet(RedisKey key,CommandFlags标志)位于c:\ TeamCity\buildAgent\work\3ae0647004edff78\StackExchange.Redis\StackExchange\Redis\RedisDatabase.cs:1431 xx.Utils.SampleStackExchangeRedisExtensions.Get(IDatabase cache,String key)位于C:\ Proyectos\xx\xx\Utils\SampleStackExchangeRedisExtensions.cs:20
xx.Cache.UserProfile.GetUserProfile(String identityname)in C:\Proyectos\xx\xx\Cache\UserProfile.cs:22
x.Controllers.UserProfileController.GetPropertiesForUser()在C:\ Proyectos\xx\xx\Controllers\UserProfileController.cs:16
lambda_method(Closure,ControllerBase,Object []) +61
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase控制器,Object []参数)+14
这是代码
public static Models.UserProfile GetUserProfile(string identityname)
{
/// It needs to be cached for every user because every user can have different modules enabled.
var cachekeyname = "UserProfileInformation|" + identityname;
IDatabase cache = CacheConnectionHelper.Connection.GetDatabase();
Models.UserProfile userProfile = new Models.UserProfile();
object obj = cache.Get(cachekeyname);
string userProfileString;
if (obj != null)
{
//get string from cache
userProfileString = obj.ToString();
//conver string to our object
userProfile = JsonConvert.DeserializeObject<Models.UserProfile>(userProfileString);
return userProfile;
}
else
{
#region Get User Profile from AD
Uri serviceRoot = new Uri(SettingsHelper.AzureAdGraphApiEndPoint);
var token = AppToken.GetAppToken();
ActiveDirectoryClient adClient = new ActiveDirectoryClient(
serviceRoot,
async () => await AppToken.GetAppTokenAsync());
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
Microsoft.Azure.ActiveDirectory.GraphClient.Application app = (Microsoft.Azure.ActiveDirectory.GraphClient.Application)adClient.Applications.Where(
a => a.AppId == SettingsHelper.ClientId).ExecuteSingleAsync().Result;
if (app == null)
{
throw new ApplicationException("Unable to get a reference to application in Azure AD.");
}
string requestUrl = string.Format("https://graph.windows.net/{0}/users/{1}?api-version=1.5", SettingsHelper.Tenant, identityname);
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage hrm = hc.GetAsync(new Uri(requestUrl)).Result;
if (hrm.IsSuccessStatusCode)
{
Models.UserProfile currentUserProfile = JsonConvert.DeserializeObject<Models.UserProfile>(hrm.Content.ReadAsStringAsync().Result);
//convert object to json string
userProfileString = JsonConvert.SerializeObject(currentUserProfile);
cache.Set(cachekeyname, userProfileString, TimeSpan.FromMinutes(SettingsHelper.CacheUserProfileMinutes));
return currentUserProfile;
}
else
{
return null;
}
#endregion
}
}
public static class SampleStackExchangeRedisExtensions
{
public static T Get<T>(this IDatabase cache, string key)
{
return Deserialize<T>(cache.StringGet(key));
}
public static object Get(this IDatabase cache, string key)
{
return Deserialize<object>(cache.StringGet(key));
}
public static void Set(this IDatabase cache, string key, object value, TimeSpan expiration)
{
cache.StringSet(key, Serialize(value), expiration);
}
static byte[] Serialize(object o)
{
if (o == null)
{
return null;
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, o);
byte[] objectDataAsStream = memoryStream.ToArray();
return objectDataAsStream;
}
}
static T Deserialize<T>(byte[] stream)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
if (stream == null)
return default(T);
using (MemoryStream memoryStream = new MemoryStream(stream))
{
T result = (T)binaryFormatter.Deserialize(memoryStream);
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是:1.如何控制如所示的连接异常,以便用户不会收到错误,如果redis不可用则转到数据库?2.无论如何,重新尝试使用azure redis缓存进行瞬态故障处理?
我相信这些是短暂的错误.在实现简单的重试逻辑之前,我在应用程序日志中看到了很多这些.我也有很多超时.非常简单的重试逻辑,再加syncTimeout=3000上redis连接字符串解决了所有这些问题.
public object Get(string key)
{
return Deserialize(Cache.StringGet(key));
}
public object GetWithRetry(string key, int wait, int retryCount)
{
int i = 0;
do
{
try
{
return Get(key);
}
catch (Exception)
{
if (i < retryCount + 1)
{
Thread.Sleep(wait);
i++;
}
else throw;
}
}
while (i < retryCount + 1);
return null;
}
Run Code Online (Sandbox Code Playgroud)