数据库读写分离,用单例工厂实现

工程代码:

添加类:SingleContextFactory

 /// 
    /// 加了互斥锁的上限文工厂
    /// 
    class SingleContextFactory : IContextFactory {
        private bool against = false;
        public static readonly string masterContext = ConfigurationManager.AppSettings["MasterContext"];
        public static readonly List slaveContexts = ConfigurationManager.AppSettings["SlaveContexts"].Split(',').ToList();
        private static Random random = new Random();
        private readonly object obj = new object();
        private readonly static object interceptorLock = new object();
        private static bool interceptorFlag = false;

        public SingleContextFactory () {
            lock (interceptorLock) {
                if (!interceptorFlag) {
                    interceptorFlag = true;
                    DbInterception.Add(new DbMasterSlaveCommandInterceptor());
                }
            }
        }
        public DBBContext CreateMasterContext () {
            lock (obj) {
                if (against) {
                    throw new InvalidOperationException("slave context has been created");
                } else {
                    against = true;
                    return new DBBContext(masterContext);
                }
            }
        }
        public DBBContext CreateSlaveContext () {
            lock (obj) {
                if (against) {
                    throw new InvalidOperationException("master context has been created");
                } else {
                    against = true;
                    int index = random.Next(0, slaveContexts.Count);
                    DBBContext context =  new DBBContext(slaveContexts[index]);
                    context.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                    return context;
                }
            }
        }
    }

再添加类:ContextFactoryFactory

public class ContextFactoryFactory {

        /// 
        /// 主库,考虑读写分离的时候这个库可度可写
        /// 
        /// 

        public static DBBContext CreateMasterContext () {
            return new SingleContextFactory().CreateMasterContext();
        }

        /// 
        /// 从库 此库只做读操作不能写
        /// 
        /// 
        public static DBBContext CreateSlaveContext () {
            return new SingleContextFactory().CreateSlaveContext();
        }
    }

拦截类:DbMasterSlaveCommandInterceptor

 /// 
    /// 从库只读 写的时候做拦截
    /// 
    class DbMasterSlaveCommandInterceptor : DbCommandInterceptor {
        private readonly string masterConnectionString;
        private readonly List slaveConnectionStrings = new List();
        private readonly Random random = new Random();

        public DbMasterSlaveCommandInterceptor() {
            this.masterConnectionString = ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["MasterContext"]].ConnectionString;
            List slaveContexts = ConfigurationManager.AppSettings["SlaveContexts"].Split(',').ToList();
            foreach (string context in slaveContexts) {
                this.slaveConnectionStrings.Add(ConfigurationManager.ConnectionStrings[context].ConnectionString);
            }
        }

        public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) {
            //this.UpdateConnectionString(interceptionContext, this.CreateSlaveConnectString());
        }
        public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) {
            //this.UpdateConnectionString(interceptionContext, this.CreateSlaveConnectString());
        }
        public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) {
            if (slaveConnectionStrings.Contains(command.Connection.ConnectionString)) {
               // 记住如果是正式读写分离的时候一定要开启
               throw new InvalidOperationException("cant update slave sqlserver");
            }
        }
        private void UpdateConnectionString(DbInterceptionContext interceptionContext, string connectionString) {
            foreach (var context in interceptionContext.DbContexts) {
                this.UpdateConnectionString(context.Database.Connection, connectionString);
            }
        }
        private string CreateSlaveConnectString() {
            string slaveConnectionString = this.slaveConnectionStrings[this.random.Next(0, this.slaveConnectionStrings.Count)];
            return slaveConnectionString;
        }

        private void UpdateConnectionString(DbConnection conn, string connectionString) {
            ConnectionState state = conn.State;
            if (state == ConnectionState.Open)
                conn.Close();
            conn.ConnectionString = connectionString;
            if (state == ConnectionState.Open)
                conn.Open();
        }
    } 
  

当然数据库的链接是自己在webconfig中配置:

 
    
    
    
  

最后在Service中使用的时候:(下面例子是读,写用master)

using (DBBContext db = ContextFactoryFactory.CreateSlaveContext()) 
{
    db.DataTable.Where(o=>...);

}

 

你可能感兴趣的:(C#)