|
- using ServiceStack.Redis;
- using System.Diagnostics;
-
- namespace Communication
- {
- public class RedisHelper
- {
-
- private volatile static RedisHelper _Instance;
- public static RedisHelper GetInstance => _Instance ?? (_Instance = new RedisHelper());
- private RedisHelper() { }
- RedisClient client;
-
- public async Task<bool> ConnectAsync()
- {
- return await Task.Factory.StartNew(new Func<bool>(() =>
- {
- if (client == null)
- {
- BPASmartClient.Message.MessageLog.GetInstance.ShowDebugLog("开始连接 Redis");
- client = new RedisClient("124.222.238.75", 16000, "123456", 1);
- client.ConnectTimeout = 5000;
- Stopwatch sw = new Stopwatch();
- sw.Start();
- while (!client.IsSocketConnected())
- {
- if (sw.ElapsedMilliseconds >= client.ConnectTimeout) break;
- Thread.Sleep(1000);
- }
- string status = client.IsSocketConnected() ? "成功" : "失败";
- BPASmartClient.Message.MessageLog.GetInstance.ShowDebugLog($"Redis 连接{status}");
- }
- return client.IsSocketConnected();
- }));
-
- }
-
- /// <summary>
- /// 清除所有redis 数据
- /// </summary>
- public void FlushDb()
- {
- client?.FlushDb();
- }
-
- /// <summary>
- /// 设置值
- /// </summary>
- /// <typeparam name="TValue"></typeparam>
- /// <param name="key"></param>
- /// <param name="value"></param>
- public void SetValue<TValue>(string key, TValue value)
- {
- var res = client?.Set<TValue>(key, value);
- }
-
- /// <summary>
- /// 获取值
- /// </summary>
- /// <typeparam name="TResult"></typeparam>
- /// <param name="key"></param>
- /// <returns></returns>
- public TResult GetValue<TResult>(string key)
- {
- if (client == null) return default(TResult);
- return client.Get<TResult>(key);
- }
-
- }
- }
|