1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| public class RedisConnector { public class RedisParseResult<T> { public bool success; public T value; }
private static string ConnectionString { get; set; } private static ConnectionMultiplexer RedisConnection { get; set; }
public RedisConnector(string redisConnectionString) { ConnectionString = redisConnectionString; try { RedisConnection = ConnectionMultiplexer.Connect(ConnectionString); } catch (RedisConnectionException e) { AILogger.LogError(e.Message, $"Redis server : {redisConnectionString}").Wait(); } }
public static void Initialize(string redisConnectionString) { ConnectionString = redisConnectionString; try { RedisConnection = ConnectionMultiplexer.Connect(ConnectionString); } catch (RedisConnectionException e) { AILogger.LogError(e.Message, $"Redis server : {redisConnectionString}").Wait(); } }
public static IDatabase RedisStore => (null != RedisConnection) ? RedisConnection.GetDatabase() : ConnectionMultiplexer.Connect(ConnectionString).GetDatabase();
public static ConnectionMultiplexer Redis => RedisConnection ?? ConnectionMultiplexer.Connect(ConnectionString);
public async static Task<bool> Store(string key, string value, int expiry = 120, bool replace = false) => await RedisStore.StringSetAsync(key, value, TimeSpan.FromSeconds(expiry), replace ? When.Always : When.NotExists);
public async static Task<bool> Store(string key, long value, int expiry = 120, bool replace = false) => await RedisStore.StringSetAsync(key, value.ToString(), TimeSpan.FromSeconds(expiry), replace ? When.Always : When.NotExists);
public async static Task<bool> Store<T>(string key, T value, int expiry = 120, bool replace = false) => await RedisStore.StringSetAsync(key, JsonConvert.SerializeObject(value), TimeSpan.FromSeconds(expiry), replace ? When.Always : When.NotExists);
public static string Get(string key) => RedisStore.StringGet(key);
public static RedisParseResult<T> Get<T>(string key) { var storedValue = RedisStore.StringGet(key); if (string.IsNullOrEmpty(storedValue)) return new RedisParseResult<T> { success = false }; else return new RedisParseResult<T> { success = true, value = JsonConvert.DeserializeObject<T>(storedValue) }; } }
|