How can I get a key count for StackExchange.Redis?
Asked Answered
I

2

5

I have an azure redis cache. I've set it up so that I can do stringGet key setting based off this example. It works pretty great.

However, I want to know if the cache is empty or not, or if there are any entries of (x) type of a C# object I have. I currently want to see if I can get a key count. I haven't found any solutions for this.

My only idea is to do a key scan that would search for every key (a get all) and then do a count. But that seems inefficient. Is there a more "meta" data style solution?

Thanks!

Ichor answered 6/1, 2017 at 21:38 Comment(0)
E
7

Per my understanding, you could leverage IServer.Keys to retrieve all keys with matching pattern as follows:

var endpoints=ConnectionMultiplexer.GetEndPoints();
var server = ConnectionMultiplexer.GetServer(endpoints.First());
var keys = server.Keys();

For more details about keys scanning, you could refer to this tutorial.

Earthshaker answered 9/1, 2017 at 7:30 Comment(1)
Here is the all documentation about [StackExchange.Redis] (github.com/StackExchange/StackExchange.Redis), you could see here.Earthshaker
C
0

Try the following snippet of code.

It will take some time to calculate and fetch it all as its using paging by default. If you on the same network and close proximity, 4 million records should take roughly 10 seconds to return a result.

var redis = ConnectionMultiplexer.Connect(configuration);

var db = redis.GetDatabase();

var keyCount = db.Multiplexer.GetEndPoints()
   .Select(endPoint => db.Multiplexer.GetServer(endPoint))
   .Sum(server => server.Keys().Count());

Alternatively, you may also run the following command in C# to get a response from the server instantaneously.

var result = db.Execute("DBSIZE");
var keyCount = (long)result;
Coprophilia answered 29/10 at 16:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.