Redis Cache Implementation
PRE-REQUISITES:-
1.) Install Redis For Local using Below Link:-
https://github.com/microsoftarchive/redis/releases/download/win-3.2.100/Redis-x64-3.2.100.msi
2.) Redis access for a particular port in Local:-
i.e, 127.0.0.1:6379
3.) Configure Redis and Start using the service.
CODE:-
[Route("api/[controller]")]
[ApiController]
public class SearchController : ControllerBase
{
private readonly ConnectionMultiplexer _redis;
private readonly IConfiguration _configuration;
private readonly EmailSettings _emailSettings;
public SearchController(IConfiguration configuration, IOptions<EmailSettings> emailSettings)
{
_redis = ConnectionMultiplexer.Connect(configuration["RedisDb"]);
_configuration = configuration;
_emailSettings = emailSettings.Value;
}
[HttpPost("get-search-history-by-word")]
public IActionResult AddNGetToSearchHistory([FromBody]SearchHistoryRequest searchRequest)
{
string cacheKey = "SearchHistory";
IDatabase redisDb = _redis.GetDatabase();
List<string> searchHistory = SearchLogic.GetSearchHistoryFromRedis(cacheKey, redisDb, searchRequest.maxCounterForWord);
List<string> filteredSearchHistory = new List<string>();
foreach (var historyItem in searchHistory)
{
string[] parts = historyItem.Split(':');
string wordPart = parts[0];
string wordInitials = wordPart.Substring(0, Math.Min(wordPart.Length == 1 ? 1 : wordPart.Length - 1, wordPart.Length));
if (string.IsNullOrEmpty(searchRequest.word) || wordPart.Length >= searchRequest.word.Length && (searchRequest.word.StartsWith(wordInitials, StringComparison.InvariantCultureIgnoreCase)) || wordPart.Length >= searchRequest.word.Length && (wordInitials.StartsWith(searchRequest.word, StringComparison.InvariantCultureIgnoreCase)))
{
filteredSearchHistory.Add(historyItem);
}
}
// Check if the word exists in the Redis cache set
bool wordExists = redisDb.SetContains(cacheKey, searchRequest.word);
if (!string.IsNullOrEmpty(searchRequest.word) && !wordExists)
{
// Add the new word to the Redis cache set
redisDb.SetAdd(cacheKey, searchRequest.word);
// Set the initial counter value for the new word
string counterKey = $"{cacheKey}:{searchRequest.word}:counter";
redisDb.StringSet(counterKey, 1);
}
else if(wordExists)
{
//Increment the counter for the existing word
string counterKey = $"{cacheKey}:{searchRequest.word}:counter";
long counter = redisDb.StringIncrement(counterKey);
}
// to fetch 10 words only - use the below code
return Ok(filteredSearchHistory.Take(10).OrderByDescending(item => SearchLogic.GetCounterValue(item)));
// to fetch all words- use the below code
//return Ok(filteredSearchHistory);
}
[HttpPost("post-search-history")]
public IActionResult PostSearchHistory(string word)
{
string cacheKey = "SearchHistory";
IDatabase redisDb = _redis.GetDatabase();
// Check if the word exists in the Redis cache set
bool wordExists = redisDb.SetContains(cacheKey, word);
if (wordExists)
{
// Increment the counter for the existing word
string counterKey = $"{cacheKey}:{word}:counter";
long counter = redisDb.StringIncrement(counterKey);
}
else
{
// Add the new word to the Redis cache set
redisDb.SetAdd(cacheKey, word);
// Set the initial counter value for the new word
string counterKey = $"{cacheKey}:{word}:counter";
redisDb.StringSet(counterKey, 1);
}
return Ok("Word added to search history");
}
[HttpDelete("clean-search-history")]
public IActionResult CleanSearchHistory()
{
string cacheKey = "SearchHistory";
IDatabase redisDb = _redis.GetDatabase();
// Remove the cache key and associated counter keys
redisDb.KeyDelete(cacheKey);
RedisValue[] searchedWords = redisDb.SetMembers(cacheKey);
foreach (var word in searchedWords)
{
string counterKey = $"{cacheKey}:{word}:counter";
redisDb.KeyDelete(counterKey);
}
return Ok("Cache has been Cleared");
}
[HttpDelete("clean-search-history-by-word")]
public IActionResult CleanSearchHistory([FromBody] string wordToDelete)
{
if (string.IsNullOrEmpty(wordToDelete))
{
return BadRequest("Please provide a word to delete.");
}
string cacheKey = "SearchHistory";
IDatabase redisDb = _redis.GetDatabase();
// Remove the specific word from the cache set
redisDb.SetRemove(cacheKey, wordToDelete);
// Remove the associated counter key
string counterKey = $"{cacheKey}:{wordToDelete}:counter";
redisDb.KeyDelete(counterKey);
return Ok($"Word '{wordToDelete}' has been removed from the cache.");
}
}
}
Comments
Post a Comment