Skip to content

Commit

Permalink
feature : Add Cache Service
Browse files Browse the repository at this point in the history
  • Loading branch information
KTajerbashi committed Aug 3, 2024
1 parent 32a79fd commit 9fdfe04
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="StackExchange.Redis" Version="2.8.0" />
</ItemGroup>


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace AbstractionsExtensions.Library.CacheManagement.Repositories;

public interface ICacheService
{
/// <summary>
/// Get Data using key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
T GetData<T>(string key);
/// <summary>
/// Set Data with Value and Expiration Time of Key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expirationTime"></param>
/// <returns></returns>
bool SetData<T>(string key, T value, DateTimeOffset expirationTime);
/// <summary>
/// Remove Data
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
object RemoveData(string key);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using AbstractionsExtensions.Library.CacheManagement.Repositories;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace AbstractionsExtensions.Library.CacheManagement.Services;

public class CacheService : ICacheService
{
private IDatabase _db;
public CacheService()
{
ConfigureRedis();
}
private void ConfigureRedis()
{
//_db = ConnectionHelper.Connection.GetDatabase();
}
public T GetData<T>(string key)
{
var value = _db.StringGet(key);
if (!string.IsNullOrEmpty(value))
{
return JsonConvert.DeserializeObject<T>(value);
}
return default;
}
public bool SetData<T>(string key, T value, DateTimeOffset expirationTime)
{
TimeSpan expiryTime = expirationTime.DateTime.Subtract(DateTime.Now);
var isSet =_db.StringSet(key, JsonConvert.SerializeObject(value), expiryTime);
return isSet;
}
public object RemoveData(string key)
{
bool _isKeyExist = _db.KeyExists(key);
if (_isKeyExist == true)
{
return _db.KeyDelete(key);
}
return false;
}
}

0 comments on commit 9fdfe04

Please sign in to comment.