有3台负载均衡的应用服务器(a、b、c),都在跑同一套.NET代码,连接同一个数据库。由于业务上的应用需求,我打算使用
Application对象。可问题是,这3台服务器之间对于同一个Application项要如何同步?
比如我在a服务器中更新了Application[Money]项,请问另外2台服务器(b、c)的Application[Money]项会自动更新吗?
如果不能自动更新,有什么解决办法吗?
Application对象是放在本机内存的,每台机上都有一份,如果真的想用Application对象的话,你就必须自己上层封装一下,一台机器更新的时候同步更新多台机器,但是这样会失去负载均衡的动态伸缩性,不推荐这么使用,还是推荐公共的状态放到其它的持久化对象里面,如数据库,memcached或者其它noSql数据库等
不能自动更新,需要将Applicaion State保存在数据库中,web.config配置示例:
<sessionState
mode="SQLServer"
sqlConnectionString="data source=127.0.0.1;user id=<username>;password=<strongpassword>"
cookieless="false"
timeout="20"
/>
可以参考下文
http://forums.asp.net/t/1712565.aspx/1
You are getting issues while coding only. So when you deploy it doesn't really worrying you. So better leave that way. Cause the Application state stored in memory is far faster than in DB. The way i mean DB is not like the way we work with session management in sql server. Session management asp.net allows yo to store it in sql server. But Application state as per msdn article it stores in memory only(no DB). There is no built in support for Application state in DB. Again this is not something what .net needs to provide you. You can write you own logic to save and retrieve from DB. Serialize the object what you are storing in application state and insert it in DB. You can retrieve the same in Application_Start.
BTW before going to all these things, I read the following article which I mentioned above also. In this article they were speaking about StaticObjects of Application state. As we know static types scope is AppDomain. Good only. So first try StaticObjects. If this resolves your issue, no worries. If it doesn't, think again whether you want to go for sql server or not. Because the issue is occurring to you while developing/debugging only.
ApplicationState
http://msdn.microsoft.com/en-us/library/ms178594.aspx
StaticObjects
http://msdn.microsoft.com/en-us/library/system.web.httpapplicationstate.staticobjects.aspx
如果有mutex需求的话还不是建议放在application里
支持1楼
不能,可以放到1个公共的地方,比如memcached
如果你没条件,那么按照dudu的来是绝对没问题的。
如果你有条件,那么搞个redis或redis集群代替Application。