浅聊读写分离 (2)

浅聊读写分离

浅聊读写分离

public class MasterSlaveThreadLocal { //private static volatile int slaveCount = 0; private static int slaveCount = 0; private static ThreadLocal<string> threadLocal = new ThreadLocal<string>(); private static string masterConnection = ConfigurationManager.ConnectionStrings["MasterConnection"].ToString(); private static string slaveConnection0 = ConfigurationManager.ConnectionStrings["SlaveConnection0"].ToString(); private static string slaveConnection1 = ConfigurationManager.ConnectionStrings["SlaveConnection1"].ToString(); private static string slaveConnection2 = ConfigurationManager.ConnectionStrings["SlaveConnection2"].ToString(); public static void setDataSourceKey(string httpType) { if (httpType == "GET") { Interlocked.Add(ref slaveCount, 1); if (slaveCount % 3 == 0) { threadLocal.Value = slaveConnection0; } else if (slaveCount % 3 == 1) { threadLocal.Value = slaveConnection1; } else { threadLocal.Value = slaveConnection2; } } if(httpType=="POST") threadLocal.Value = masterConnection; } public static string getDataSourceKey() { return threadLocal.Value; } } /// <summary> /// 主从过滤器 /// 设置为全局过滤器 /// </summary> public class MasterSlaveFilterAttribute: ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); MasterSlaveThreadLocal.setDataSourceKey(filterContext.HttpContext.Request.HttpMethod); } } public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new MasterSlaveFilterAttribute()); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wspgjy.html