我正在使用“ Redis-x64-3.0.504”,并且试图将asp.net core 2.2 Web应用程序本地托管在IIS Express上,但是Redis缓存在IIS上无法正常运行,因为我似乎卡住了在访问或保存在缓存中时加载。但是-当我以localhost运行Visual Studio时,它运行良好。
我添加了 Microsoft.Extensions.Caching.StackExchangeRedis(2.2.5) nuget和ConfigureServices(IServiceCollection service)
中的代码进行配置。
代码如下:
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "SampleInstance";
});
然后我创建了一个CacheHelper
类作为访问缓存的方法的泛型:
public static class CacheHelper
{
public static void SaveInCache<T>(IDistributedCache memoryCache, string key, T value)
{
var graphJSON = JsonConvert.SerializeObject(value);
memoryCache.SetStringAsync(key, graphJSON);
}
public static T GetFromCache<T>(IDistributedCache memoryCache, string key)
{
var cacheValue = memoryCache.GetStringAsync(key);
return JsonConvert.DeserializeObject<T>(cacheValue.Result != null ? cacheValue.Result : string.Empty);
}
public static T GetMatchFromCache<T>(IDistributedCache memoryCache, string matchKey)
{
var redis = StackExchange.Redis.ConnectionMultiplexer.Connect("localhost");
var db = redis.GetDatabase();
var serverEndpoints = redis.GetEndPoints()[0];
var keys = redis.GetServer(serverEndpoints).Keys(pattern: "*");
foreach(var key in keys)
{
if (key.ToString().Contains(matchKey))
{
var trimmedKey = key.ToString().Substring(key.ToString().IndexOf(matchKey));
return GetFromCache<T>(memoryCache, trimmedKey);
}
}
return default(T);
}
public static List<T> GetAllMatchFromCache<T>(IDistributedCache memoryCache, string matchKey)
{
List<T> contentList = new List<T>();
var redis = StackExchange.Redis.ConnectionMultiplexer.Connect("localhost");
var db = redis.GetDatabase();
var serverEndpoints = redis.GetEndPoints()[0];
var keys = redis.GetServer(serverEndpoints).Keys(pattern: "*");
foreach (var key in keys)
{
if (key.ToString().Contains(matchKey))
{
var trimmedKey = key.ToString().Substring(key.ToString().IndexOf(matchKey));
var cacheReturn = GetFromCache<T>(memoryCache, trimmedKey);
if (cacheReturn != null)
{
contentList.Add(cacheReturn);
}
}
}
return contentList;
}
}
我很困惑,为什么它不能在IIS上运行,而是在我的本地主机上运行。如何在IIS主机上使其工作?
答案 0 :(得分:0)
在建立连接时尝试以下操作:
using (var muxer = ConnectionMultiplexer.Connect("localhost,resolvedns=1"))
{
muxer.PreserveAsyncOrder = preserveOrder;
RedisKey key = "MBOA";
var conn = muxer.GetDatabase();
muxer.Wait(conn.PingAsync());
Action<Task> nonTrivial = delegate
{
Thread.SpinWait(5);
};
var watch = Stopwatch.StartNew();
for (int i = 0; i <= AsyncOpsQty; i++)
{
var t = conn.StringSetAsync(key, i);
if (withContinuation) t.ContinueWith(nonTrivial);
}
int val = (int)muxer.Wait(conn.StringGetAsync(key));
watch.Stop();
Console.WriteLine("After {0}: {1}", AsyncOpsQty, val);
Console.WriteLine("({3}, {4})\r\n{2}: Time for {0} ops: {1}ms; ops/s: {5}", AsyncOpsQty, watch.ElapsedMilliseconds, Me(),
withContinuation ? "with continuation" : "no continuation", preserveOrder ? "preserve order" : "any order",
AsyncOpsQty / watch.Elapsed.TotalSeconds);
}
希望有帮助。