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 ConnectAsync() { return await Task.Factory.StartNew(new Func(() => { 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(); })); } /// /// 清除所有redis 数据 /// public void FlushDb() { client?.FlushDb(); } /// /// 设置值 /// /// /// /// public void SetValue(string key, TValue value) { var res = client?.Set(key, value); } /// /// 获取值 /// /// /// /// public TResult GetValue(string key) { if (client == null) return default(TResult); return client.Get(key); } } }