让Dapper读写分离


  在上一篇说了封闭Dapper扩展方法为一个接口来支持Mock,接下来看看如何实现读写分离。

  其实定义两个接口,一个用来实现读,一个用来实现写。在读的接口里只有Query的方法,在写的接口里实现Query和Execute全量(通读写的库也是支持读的,有的场景还是必须在写库里读,因为写库往读库中同步时是有时差的)。

IDapperPlusRead.cs

/// 
    /// DapperPlus读接口
    /// 
    public interface IDapperPlusRead
    {
        /// 
        /// 连接
        /// 
        public IDbConnection Connection
        {
            get;
        }
        /// 
        /// Executes a single-row query, returning the data typed as type.
        /// 
        /// The type to return.
        /// The SQL to execute for the query.
        /// The parameters to pass, if any.
        /// The transaction to use, if any.
        /// Whether to buffer results in memory.
        /// The command timeout (in seconds).
        /// The type of command to execute.
        /// A sequence of data of the supplied type; if a basic type(int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is created per row, and a direct column-name===member-name mapping is assumed(case insensitive).
        /// 异常:T:System.ArgumentNullException:type is null.
        /// 
        IEnumerable<object> Query(Type type, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null);
        //这时省略n个方法
     }

IDapperPlusWrite.cs

  /// 
    /// 写Dapper接口
    /// 
    public interface IDapperPlusWrite
    {
        /// 
        /// 连接
        /// 
        public IDbConnection Connection
        {
            get;
        }
        /// 
        /// Execute parameterized SQL.
        /// 
        /// The SQL to execute for this query.
        /// The parameters to use for this query.
        /// The transaction to use for this query.
        /// Number of seconds before command execution timeout.
        /// Is it a stored proc or a batch?
        /// The number of rows affected.
        int Execute(string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null);

        /// 
        /// Executes a single-row query, returning the data typed as type.
        /// 
        /// The type to return.
        /// The SQL to execute for the query.
        /// The parameters to pass, if any.
        /// The transaction to use, if any.
        /// Whether to buffer results in memory.
        /// The command timeout (in seconds).
        /// The type of command to execute.
        /// A sequence of data of the supplied type; if a basic type(int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is created per row, and a direct column-name===member-name mapping is assumed(case insensitive).
        /// 异常:T:System.ArgumentNullException:type is null.
        /// 
        IEnumerable<object> Query(Type type, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null);
        //这时省略n个方法
     }

  按照读写接口实现各自的类,这里就要在两个类的构造里取出各自己的连接字符串(读写库的实例或库名有所区别),这里用了个约定,就是在配置里,连接字符串的名称有read或write字样,通过这个约定来分别取读写连接字符串。

DapperPlusRead.cs

 /// 
    /// DapperPlus读实现类
    /// 
    public class DapperPlusRead : IDapperPlusRead
    {
        protected IDbConnection _connection;
        /// 
        /// 构造
        /// 
        /// 连接
        /// 配置
        public DapperPlusRead(IDbConnection connection, IConfiguration configuration)
        {            
            var connectionStrings = configuration.GetSection("ConnectionStrings").Getstring, string>>();
            _connection = connection;
            _connection.ConnectionString = connectionStrings.Where(s => s.Key.ToLower().Contains("read")).FirstOrDefault().Value;  
        }
        /// 
        /// 连接
        /// 
        public IDbConnection Connection
        {
            get
            {
                return _connection;
            }
        }

        /// 
        /// Executes a single-row query, returning the data typed as type.
        /// 
        /// The type to return.
        /// The SQL to execute for the query.
        /// The parameters to pass, if any.
        /// The transaction to use, if any.
        /// Whether to buffer results in memory.
        /// The command timeout (in seconds).
        /// The type of command to execute.
        /// A sequence of data of the supplied type; if a basic type(int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is created per row, and a direct column-name===member-name mapping is assumed(case insensitive).
        /// 异常:T:System.ArgumentNullException:type is null.
        /// 
        public IEnumerable<object> Query(Type type, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
        {
            return _connection.Query(type, sql, param, transaction, buffered, commandTimeout, commandType);
        }
        //这时省略n个方法
      }

  剩下的就是注入了,使用读时用IDapperPlusRead就可以,写就用IDapperPlusWrite。

public void ConfigureServices(IServiceCollection services)
{
     services.AddControllers();
     services.AddScoped();
     services.AddScoped();
     services.AddScoped();
}

appsettings.json

 "ConnectionStrings": {
    "ReadConnectionString": "server=127.0.0.1;uid=root;pwd=root;database=read_mysql_testdb",
    "WriteConnectionString": "server=127.0.0.1;uid=root;pwd=root;database=write_mysql_testdb"
  }
  想要更快更方便的了解相关知识,可以关注微信公众号