首页 > 代码库 > EntityFramework 实现读写分离
EntityFramework 实现读写分离
1、数据库切换器
public class RandomGet<T> { private class RandomModel { public T Value { get; set; } public RandomModel Next { get; set; } } public RandomGet(params T[] value) { if (value != null) { foreach (var item in value) { AllObject.Add(new RandomModel() { Value =http://www.mamicode.com/ item }); } } if (AllObject.Count > 0) { //创建链表 AllObject[AllObject.Count - 1].Next = AllObject[0]; for (int i = 0; i < AllObject.Count - 1; i++) { AllObject[i].Next = AllObject[i + 1]; } Current = AllObject[0]; } else { throw new ArgumentException(""); } } private List<RandomModel> AllObject { get; set; } = new List<RandomModel>(); private RandomModel Current; public T GetValue() { Current = Current.Next; //超高的并发,可能短暂的无法切换,但是也会实现数据库的切换 return Current.Value; } }
2、EntityFramework拦截器
public class BreakAwayContext : DbContext { /// <summary> /// 命令拦截器 /// </summary> public class NoLockInterceptor : DbCommandInterceptor { public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) { command.Connection.Close(); //这里的Close不会大量关闭Connection,因为C#自己的连接池机制,这里不会关闭连接 command.Connection.ConnectionString = SelectModel.GetValue(); command.Connection.Open(); } public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) { command.Connection.Close(); command.Connection.ConnectionString = SelectModel.GetValue(); command.Connection.Open(); } } static BreakAwayContext() { System.Data.Entity.Infrastructure.Interception.DbInterception.Add(new NoLockInterceptor()); //关键代码,设置拦截器 } static RandomGet<String> InsertModel = new RandomGet<String>("Data Source=192.168.0.150;Initial Catalog=MyBook;user id=root;password=123123;");//修改删除的字符串 static RandomGet<String> SelectModel = new RandomGet<String>( "Data Source=192.168.0.150;Initial Catalog=MyBook;user id=root;password=123123;" , "Data Source=192.168.0.150;Initial Catalog=MyBook;user id=root;password=123123;" , "Data Source=192.168.0.150;Initial Catalog=MyBook;user id=root;password=123123;");//查询的字符串 public BreakAwayContext() : base(InsertModel.GetValue()) //这里每个EF对象创建的时候,调用这个,获得一个连接字符串 { } public DbSet<Destination> Destinations { get; set; } }
EntityFramework 实现读写分离
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。