Home > Enterprise >  AddStackExchangeRedisCache - multiple connections created
AddStackExchangeRedisCache - multiple connections created

Time:10-29

I have a Web API in .NET 5 that uses Microsoft.Extensions.Caching.StackExchangeRedis. I have added the IDistributedCache implementation of Redis cache using an extension method from the given package.

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = Configuration.GetConnectionString("RedisConnection");
});

Now, when I request something from Redis (and since it's a singleton), it should create 1 connection due to the inner implementation (Github link) of IDistributedCache performing ConnectionMultiplexer.Connect() once. However, when I use redis-cli and perform the client list command, it lists me 3 total connections (1 of me currently connected via redis-cli and the other two from the API. Should that be happening at all since it's, well, 1 connection really?

127.0.0.1:6379> client list
id=6 addr=127.0.0.1:4396 fd=9 name= age=3305 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 events=r cmd=client
127.0.0.1:6379> client list
id=6 addr=127.0.0.1:4396 fd=9 name= age=3317 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 events=r cmd=client
id=11 addr=127.0.0.1:1046 fd=12 name=PC age=4 idle=3 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=hmget
id=12 addr=127.0.0.1:1048 fd=11 name=PC age=4 idle=4 flags=N db=0 sub=1 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=subscribe

CodePudding user response:

If you look at the second SE.Redis connection, it's a subscriber:

id=12 addr=127.0.0.1:1048 fd=11 name=PC age=4 idle=4 flags=N db=0 sub=1 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=subscribe

Under the hood, SE.Redis is setting itself up to listen to events published through redis, in particular, I think it's setting itself up to hear from other SE.Redis instances that the master has changed. In theory, if there is a failover, one of the SE.Redis instances will detect it and will publish to the channel __Booksleeve_MasterChanged, which will signal to the other instances to failover. There's only 1 connection that you will send things over but the subscriber connection will be used for that other stuff. You can run redis-cli monitor to see the subscriptions coming through from SE.Redis.

  • Related