Check whether a Key exists in Redis
IDatabase.KeyExists(string key)
Purpose: Check whether the specified key exists in Redis
- Return
true: the key exists - Return
false: the key does not exist
It returns true as long as the key exists, works for all data types (applies to String, List, Hash and other types)
/// <summary>
/// Check if cache key exists
/// </summary>
/// <param name="key">Cache key name</param>
/// <returns>true if exists, false if not exists</returns>
private bool IsSet(string key)
{
return db.KeyExists(key);
}Code language: PHP (php)
Example
string cacheKey = "user:1001";
if(IsSet(cacheKey))
{
// Key exists, read cache directly
var user = Get<User>(cacheKey);
}
else
{
// Key not exists, query database and write to Redis
var user = QueryDbUser(1001);
Set(cacheKey, user, 30);
}Code language: JavaScript (javascript)
Check existence
Previous: Read value