private void Intialize() { try { LibPath = ""; PythonRootPath = ConfigUtils.GetSetting("PythonRootPath", "PyScript"); _runtimePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; _runtimePath = Path.Combine(_runtimePath, PythonRootPath); _routeConfigFileName = Path.Combine(_runtimePath, "Route.config.xml"); CacheListener routeListener = new CacheListener("__ACTION_ROUTES", 0, (key, value, reason) => { if (reason == CacheItemRemovedReason.DependencyChanged) { LoadRouteConfig(_routeConfigFileName); //重新设置查找路径 PythonScriptHost.LibPath = LibPath; PythonScriptHost.SetPythonSearchPath(_runtimePath); } }, _routeConfigFileName); routeListener.Start(); LoadRouteConfig(_routeConfigFileName); bool isDebug = ConfigUtils.GetSetting("Python_IsDebug", "false").ToBool(); PythonScriptHost.Initialize(_runtimePath, LibPath, isDebug); } catch (Exception ex) { TraceLog.WriteError("ActionFactory load route config:{0} error{1}", _routeConfigFileName, ex); } }
/// <summary>删除一条数据 /// /// </summary> public bool Delete(int Id) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from CacheConfig "); strSql.Append(" where Id=@Id "); IDbHelper h = GlobalHelp.GetDataAccessHelper(); #region 缓存配置行 h.CreateCommand("select * from CacheConfig where id =" + Id + ""); DataTable dt = h.ExecuteQuery(); dt.TableName = "CacheConfig"; #endregion h.CreateCommand(strSql.ToString()); h.AddParameter("@Id", Id); bool blnReturn = h.ExecuteNonQuery(); if (blnReturn) { #region 修改缓存配置:如果是则需要推送更新缓存的消息。即是发消息告诉服务端我修改了缓存配置,让服务端统一向所有在线客户端发送更新缓存消息 string strCacheTableName = dt.Rows[0]["CacheTableName"].ToString(); CacheMessageEntity messageEntity = new CacheMessageEntity { CacheKey = strCacheTableName, Operation = "Delete", DataTableCache = dt }; CacheListener.AddMessage(messageEntity); #endregion } return(blnReturn); }
private static void Main() { BindExceptionHandler();//绑定程序中的异常处理 System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); #region Autoface注册接口 var builder = new ContainerBuilder(); //var assembly = Assembly.GetAssembly(basetype); var assembly = Assembly.LoadFile(Path.Combine(Application.StartupPath, "Nikita.Platform.BugClose.DAL.dll")); Assembly[] arrAssemblies = new Assembly[1]; arrAssemblies[0] = assembly; builder.RegisterAssemblyTypes(arrAssemblies).AsImplementedInterfaces(); GlobalHelp.Container = builder.Build(); #endregion Autoface注册接口 //System.Windows.Forms.Application.Run(new FrmTestCache()); FrmLogin login = new FrmLogin(); if (login.ShowDialog() == DialogResult.OK) { login.Close(); if (CacheManager.AllowCache) { //同步缓存 CacheManager.SynCache(); //开始监听缓存 CacheListener.StartClient(); } System.Windows.Forms.Application.Run(new FrmBugCloseMainForm()); } }
protected override void OnStart(string[] args) { string pathToConfigFile = ConfigurationManager.AppSettings["CacheConfigFile"]; CacheHelper.InitPerformanceCounters(); this.listener = new CacheListener(pathToConfigFile); var task = listener.StartAsync(); }
/// <summary> /// 停止缓存写库监听 /// </summary> public static void StopListener() { if (_cacheExpiredListener != null) { _cacheExpiredListener.Stop(); _cacheExpiredListener = null; } if (_cacheUpdateListener != null) { _cacheUpdateListener.Stop(); _cacheUpdateListener = null; } //System.Threading.Interlocked.Exchange(ref _isDisposed, 1); TraceLog.WriteLine("CacheFactory listen has stoped"); }
private static void InitListener(string listenerKey, int expiredInterval, string updateListentKey, int updateInterval) { if (enableUpdateListent && _cacheUpdateListener == null) { _cacheUpdateListener = new CacheListener(updateListentKey, updateInterval, (key, value, reason) => { try { if (!_isRunning) { _isRunning = true; TraceLog.WriteLine("{0} Cache sync to storage start...", DateTime.Now.ToString("HH:mm:ss")); UpdateNotify(true); TraceLog.WriteLine("{0} Cache sync to storage end.", DateTime.Now.ToString("HH:mm:ss")); _isRunning = false; } else { TraceLog.WriteLine("{0} Cache sync to storage doing...", DateTime.Now.ToString("HH:mm:ss")); } } catch (Exception ex) { TraceLog.WriteError("Cache manager timing error:{0}", ex); } }); } if (_cacheExpiredListener == null) { _cacheExpiredListener = new CacheListener(listenerKey, expiredInterval, (key, value, reason) => { if (reason == CacheRemovedReason.Expired) { try { _readonlyPools.DisposeCache(); _writePools.DisposeCache(); TraceLog.WriteLine("{0} Clear expired cache end.", DateTime.Now.ToString("HH:mm:ss")); } catch (Exception ex) { TraceLog.WriteError("Cache manager timing error:{0}", ex); } } }); } }
private static void InitListener(string listenerKey, int expiredInterval, string updateListentKey, int updateInterval) { if (enableUpdateListent && _cacheUpdateListener == null) { _cacheUpdateListener = new CacheListener(updateListentKey, updateInterval, (key, value, reason) => { try { if (!_isRunning) { _isRunning = true; TraceLog.ReleaseWrite("缓存延迟更新执行开始"); UpdateNotify(true); TraceLog.ReleaseWrite("缓存延迟更新执行结束"); _isRunning = false; } else { TraceLog.ReleaseWrite("缓存延迟更新正在执行中..."); } } catch (Exception ex) { TraceLog.WriteError("Cache manager timing error:{0}", ex); } }); } if (_cacheExpiredListener == null) { _cacheExpiredListener = new CacheListener(listenerKey, expiredInterval, (key, value, reason) => { if (reason == CacheRemovedReason.Expired) { try { _readonlyPools.DisposeCache(); _writePools.DisposeCache(); TraceLog.ReleaseWrite("清理过期缓存结束..."); } catch (Exception ex) { TraceLog.WriteError("Cache manager timing error:{0}", ex); } } }); } }
/// <summary> /// 初始化配置 /// </summary> public static void Intialize() { string runtimePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; _configFileName = Path.Combine(runtimePath, "Game.config.xml"); CacheListener routeListener = new CacheListener("__GAME_CONFIG", 0, (key, value, reason) => { if (reason == CacheRemovedReason.Changed) { _gameConfigSetting.Init(_configFileName); } }, _configFileName); routeListener.Start(); _gameConfigSetting.Init(_configFileName); }
/// <summary> /// /// </summary> /// <param name="secondTimeOut"></param> public static void Start(int secondTimeOut) { _cacheListener = new CacheListener(CacheKey, secondTimeOut, (key, value, reason) => { if (reason == CacheRemovedReason.Expired) { if (Interlocked.Exchange(ref _running, 1) == 0) { DoRefresh(); Interlocked.Exchange(ref _running, 0); } } }); DoRefresh(); _cacheListener.Start(); }
/// <summary> /// /// </summary> public SocketListener(SocketSettings settings) { _settings = settings; _sessioinListen = new CacheListener("__SOCKET_SESSION_POOL", 10, OnRemoveSession); _resetEvent = new AutoResetEvent[1]; _resetEvent[0] = new AutoResetEvent(false); _sessionPool = new SocketSessionPool(); _readWritePool = new SocketAsyncPool(_settings.NumOfSaeaForRecSend); _acceptPool = new SocketAsyncPool(_settings.MaxConnection); int numSize = settings.NumOfSaeaForRecSend * settings.BufferSize; _bufferManager = new BufferManager(numSize, settings.BufferSize); _saeaProxy = new SocketAsyncEventArgsProxy(settings.BufferSize); _saeaProxy.ReceiveCompleted += OnReceiveCompleted; _saeaProxy.SendCompleted += OnSendCompleted; _saeaProxy.ClosedHandle += OnSocketClosing; Init(); }
public IEnumerator TestDataLockCached() { var cacher = new DummyCacher(); var listeners = new CacheListener <DummyCacherData> [3]; for (int i = 0; i < listeners.Length; i++) { listeners[i] = cacher.Request("a"); } yield return(new WaitForSeconds(1.5f)); Assert.IsTrue(cacher.IsCached("a")); for (int i = 0; i < listeners.Length - 1; i++) { cacher.Remove(listeners[i]); } Assert.IsTrue(cacher.IsCached("a")); cacher.Remove(listeners[2]); Assert.IsFalse(cacher.IsCached("a")); Assert.IsTrue(listeners[listeners.Length - 1].Value.IsDestroyed); }
/// <summary>增加一条数据 /// /// </summary> public int Add(Nikita.Base.CacheStore.Model.CacheConfig model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into CacheConfig("); strSql.Append("ConnectionString, TableName, Filter, CacheTableName, CacheChekGuid, CacheVersion, CreateUser, CreateDate, Remark, Status )"); strSql.Append(" values ("); strSql.Append("@ConnectionString, @TableName, @Filter, @CacheTableName, @CacheChekGuid, @CacheVersion, @CreateUser, @CreateDate, @Remark, @Status )"); strSql.Append(";select @@IDENTITY"); IDbHelper h = GlobalHelp.GetDataAccessHelper(); h.CreateCommand(strSql.ToString()); if (model.ConnectionString == null) { h.AddParameter("@ConnectionString", DBNull.Value); } else { h.AddParameter("@ConnectionString", model.ConnectionString); } if (model.TableName == null) { h.AddParameter("@TableName", DBNull.Value); } else { h.AddParameter("@TableName", model.TableName); } if (model.Filter == null) { h.AddParameter("@Filter", DBNull.Value); } else { h.AddParameter("@Filter", model.Filter); } if (model.CacheTableName == null) { h.AddParameter("@CacheTableName", DBNull.Value); } else { h.AddParameter("@CacheTableName", model.CacheTableName); } if (model.CacheChekGuid == null) { h.AddParameter("@CacheChekGuid", DBNull.Value); } else { h.AddParameter("@CacheChekGuid", model.CacheChekGuid); } if (model.CacheVersion == null) { h.AddParameter("@CacheVersion", DBNull.Value); } else { h.AddParameter("@CacheVersion", model.CacheVersion); } if (model.CreateUser == null) { h.AddParameter("@CreateUser", DBNull.Value); } else { h.AddParameter("@CreateUser", model.CreateUser); } if (model.CreateDate == null) { h.AddParameter("@CreateDate", DBNull.Value); } else { h.AddParameter("@CreateDate", model.CreateDate); } if (model.Remark == null) { h.AddParameter("@Remark", DBNull.Value); } else { h.AddParameter("@Remark", model.Remark); } if (model.Status == null) { h.AddParameter("@Status", DBNull.Value); } else { h.AddParameter("@Status", model.Status); } model.CacheChekGuid = Guid.NewGuid().ToString(); int intResult; string obj = h.ExecuteScalar(); if (!int.TryParse(obj, out intResult)) { return(0); } #region 新增缓存配置:如果是则需要推送更新缓存的消息。。即是发消息告诉服务端我修改了缓存配置,让服务端统一向所有在线客户端发送更新缓存消息 h.CreateCommand("select * from CacheConfig where id =" + intResult + ""); DataTable dt = h.ExecuteQuery(); dt.TableName = "CacheConfig"; CacheMessageEntity messageEntity = new CacheMessageEntity { CacheKey = model.CacheTableName, Operation = "Add", DataTableCache = dt }; CacheListener.AddMessage(messageEntity); #endregion return(intResult); }
static GameContext() { Listener = new CacheListener("gamecontext_listener", 1800, DoCacheDispose); Listener.Start(); }
static void Main(string[] args) { // -help // -test // -testclient config.txt // -server config.txt // -add // -remove TODO // -list // if (args.Length >= 1 && args[0].ToLower().Equals("-test")) { bool allPassed = true; bool ok = TestMaxMem(); allPassed = allPassed && ok; if (ok) { Console.WriteLine("TestMaxMem passed"); } else { Console.WriteLine("TestMaxMem failed"); } ok = TestConsistentHash(); allPassed = allPassed && ok; if (ok) { Console.WriteLine("TestConsistentHash passed"); } else { Console.WriteLine("TestConsistentHash failed"); } ok = TestCacheRing(); allPassed = allPassed && ok; if (ok) { Console.WriteLine("TestCacheRing passed"); } else { Console.WriteLine("TestCacheRing failed"); } if (args.Length > 2 && args[1].ToLower().Equals("-config")) { CacheConfig config = CacheConfig.Load(args[2]); Console.WriteLine("Config loaded Ok"); } if (allPassed) { Console.WriteLine("All Tests Passed!"); } else { Console.WriteLine("Some Tests Failed!"); } } else if (args.Length >= 1 && args[0].ToLower().Equals("-testclient")) { if (args.Length != 2) { Console.WriteLine("Missing master hostname:port. See usage:"); Usage(); return; } // It's cheating to use anything from LoopCacheLib for client tests. // Developers can use this code as an example of how to use the API. // LoopCacheLib will *not* be referenced by client applications. CacheClient client = new CacheClient(args[1]); if (client.Test()) { Console.WriteLine("All client tests passed"); } else { Console.WriteLine("Client test failed!"); } } else if (args.Length >= 1 && args[0].ToLower().Equals("-test3")) { if (args.Length != 2) { Console.WriteLine("Missing master hostname:port. See usage:"); Usage(); return; } // It's cheating to use anything from LoopCacheLib for client tests. // Developers can use this code as an example of how to use the API. // LoopCacheLib will *not* be referenced by client applications. CacheClient client = new CacheClient(args[1]); if (client.TestThreeNodes()) { Console.WriteLine("All client tests passed"); } else { Console.WriteLine("Client test failed!"); } } else if (args.Length >= 1 && args[0].ToLower().Equals("-server")) { if (args.Length != 2) { Console.WriteLine("Expected config file location. See usage:"); Usage(); return; } // Load config and dump it to the console while in development. // We can remove this later CacheConfig config = CacheConfig.Load(args[1]); Console.WriteLine("About to start server with these settings: {0}", config.GetTrace()); CacheHelper.InitPerformanceCounters(); CacheListener listener = new CacheListener(args[1]); var task = listener.StartAsync(); Console.WriteLine("Press Enter to stop"); Console.ReadLine(); listener.Stop(); Console.WriteLine("After Stop"); bool result = task.Result; Console.WriteLine("Got result {0}", result); } else if (args.Length >= 1 && args[0].ToLower().Equals("-add")) { if (args.Length != 4) { Usage(); return; } string masterHostPortStr = args[1]; string newNodeHostPortStr = args[2]; string maxNumBytesStr = args[3]; CacheClient client = new CacheClient(masterHostPortStr); long maxNumBytes; if (!long.TryParse(maxNumBytesStr, out maxNumBytes)) { Console.WriteLine("New node maxNumBytes should be a long"); Usage(); return; } if (client.AddNode(newNodeHostPortStr, maxNumBytes)) { Console.WriteLine("New node added"); } else { Console.WriteLine("Unable to add new node, check master server logs"); } } else if (args.Length >= 1 && args[0].ToLower().Equals("-list")) { if (args.Length != 2) { Console.WriteLine("Missing master hostname:port. See usage:"); Usage(); return; } CacheClient client = new CacheClient(args[1]); client.PrintList(); } else if (args.Length >= 1 && args[0].ToLower().Equals("-testservice")) { if (args.Length != 2) { Console.WriteLine("Missing node hostname:port. See usage:"); Usage(); return; } CacheClient client = new CacheClient(args[1]); // Make sure the node is listening if (!client.Ping()) { Console.WriteLine("Unable to ping master node"); return; } if (!client.GetConfig()) { Console.WriteLine("Unable to get ring configuration"); return; } bool allTestsPassed = true; List <Guid> testObjects = new List <Guid>(); for (int i = 0; i < 1000; i++) { Guid g = Guid.NewGuid(); testObjects.Add(g); } // Put the objects Parallel.ForEach(testObjects, g => { var ok = client.PutObject(g.ToString(), g.ToString()); //Console.WriteLine("Put object {0}: {1}", // g.ToString(), ok); if (!ok) { allTestsPassed = false; } }); Console.WriteLine("Done putting objects"); if (!allTestsPassed) { Console.WriteLine("Some puts failed"); return; } // Delete the objects Parallel.ForEach(testObjects, g => { var ok = client.DeleteObject(g.ToString()); //Console.WriteLine("Deleted object {0}: {1}", // g.ToString(), ok); if (!ok) { allTestsPassed = false; } }); Console.WriteLine("Done deleting objects"); if (!allTestsPassed) { Console.WriteLine("Some deletes failed"); return; } if (allTestsPassed) { Console.WriteLine("All puts and deletes succeeded"); } } else if (args.Length >= 1 && args[0].ToLower().Equals("-reperf")) { CacheHelper.RemovePerformanceCounters(); CacheHelper.InitPerformanceCounters(); } else if (args.Length >= 1 && args[0].ToLower().Equals("-automaster")) { CacheConfig config = AutoConfigMaster(); Console.WriteLine("About to start server with these settings: {0}", config.GetTrace()); CacheHelper.InitPerformanceCounters(); CacheListener listener = new CacheListener(config); var task = listener.StartAsync(); Console.WriteLine("Press Enter to stop"); Console.ReadLine(); listener.Stop(); Console.WriteLine("After Stop"); bool result = task.Result; Console.WriteLine("Got result {0}", result); } else if (args.Length >= 1 && args[0].ToLower().Equals("-autonode")) { int portNumber = int.Parse(args[1]); CacheConfig config = AutoConfigNode(portNumber); Console.WriteLine("About to start server with these settings: {0}", config.GetTrace()); CacheHelper.InitPerformanceCounters(); CacheListener listener = new CacheListener(config); var task = listener.StartAsync(); Console.WriteLine("Press Enter to stop"); Console.ReadLine(); listener.Stop(); Console.WriteLine("After Stop"); bool result = task.Result; Console.WriteLine("Got result {0}", result); } else { Usage(); return; } Console.WriteLine("Main end"); }
internal void RegisterCacheListener(CacheListener listener) { logger.Log("Adding cache listener: " + listener); this.cacheListeners.Add(listener); }
internal void RemoveCacheListener(CacheListener updateListener) { logger.Log("Removing cache listener " + updateListener); this.cacheListeners.Remove(updateListener); }