Created
March 22, 2020 18:51
-
-
Save mehmetcantas/a2b3681f0f5f438c6b6337da73fadb32 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using Newtonsoft.Json; | |
using StackExchange.Redis; | |
namespace RedisNetApi.Caching | |
{ | |
public class RedisProvider : IRedisProvider | |
{ | |
//string tipinde alınan veriyi deserialize ederek T tipinde bir objeye çevirir. | |
public T Get<T>(IDatabase cache, string key) | |
{ | |
try | |
{ | |
var value = cache.StringGet(key); | |
return !value.IsNull ? JsonConvert.DeserializeObject<T>(value) : default(T); | |
} | |
catch (Exception ex) | |
{ | |
Debug.WriteLine(ex.Message); | |
throw; | |
} | |
} | |
// parametre olarak verilen cache anahtarının geçtiği tüm cache'leri temizler. | |
public bool DeleteCacheKeyContains(IDatabase database, string keyPattern, | |
string connectionString = "127.0.0.1") | |
{ | |
try | |
{ | |
using (var redis = ConnectionMultiplexer.Connect(connectionString)) | |
{ | |
var endpoints = redis.GetEndPoints(true); | |
foreach (var endpoint in endpoints) | |
{ | |
var server = redis.GetServer(endpoint); | |
if (server == null) continue; | |
foreach (var key in server.Keys(pattern: "*." + keyPattern + ".*")) | |
{ | |
database.KeyDelete(key); | |
} | |
} | |
} | |
return true; | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e); | |
return false; | |
} | |
} | |
// parametre olarak verilen cache anahtarının temsil ettiği veriyi Redis'e aktarıyoruz. object olarak gelen veriyi önce serialize edip json'a çevirip, cache'te kalma süresini belirtiyoruz. | |
public void Set(IDatabase cache, string key, object value, TimeSpan experation) | |
{ | |
cache.StringSet(key, JsonConvert.SerializeObject(value), experation); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment