Asp.net core Redis:如何配置Redis实例
我有一个Redis实例,我希望StackExchange.Redis连接到该特定实例,但我找不到任何配置来设置InstanceName 您可以使用如下扩展方法:Asp.net core Redis:如何配置Redis实例,asp.net-core,redis,stackexchange.redis,Asp.net Core,Redis,Stackexchange.redis,我有一个Redis实例,我希望StackExchange.Redis连接到该特定实例,但我找不到任何配置来设置InstanceName 您可以使用如下扩展方法: public static IServiceCollection AddRedisQueue(this IServiceCollection services, IConfiguration configuration) { var options = configuration.GetOptions<Re
public static IServiceCollection AddRedisQueue(this IServiceCollection services, IConfiguration configuration)
{
var options = configuration.GetOptions<RedisOptions>(SectionName);
var multiplexer = ConnectionMultiplexer.Connect(options.ConnectionString);
services.AddSingleton<IConnectionMultiplexer>(multiplexer);
return services;
}
services.AddRedisQueue(Configuration);
然后您可以将其注入Startup.csConfigureServices方法,如下所示:
public static IServiceCollection AddRedisQueue(this IServiceCollection services, IConfiguration configuration)
{
var options = configuration.GetOptions<RedisOptions>(SectionName);
var multiplexer = ConnectionMultiplexer.Connect(options.ConnectionString);
services.AddSingleton<IConnectionMultiplexer>(multiplexer);
return services;
}
services.AddRedisQueue(Configuration);
稍后在代码中,您只需从要使用redis的类的构造函数中注入IConnectionMultiplexer,并通过调用IConnectionMultiplexer的GetDatabase()方法来获取数据库。关于redis options的实例属性,在提供密钥时使用该属性:
var key = $"{redisOptions.Value.Instance}some_key";
然后在处理堆栈交换的IDatabase实例时使用此键。请详细说明我应该在哪里使用RedisOptions的属性“instance”?此属性未在您提供的代码的AddRedisQueue中使用@阿斯普拉米,谢谢。是否有任何配置,我可以设置,使我不必每次手动添加“实例名”@AspramAs,我知道只有在使用IDistributedCache时才能使用它。