ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

让Dapper读写分离

2022-02-05 15:31:32  阅读:171  来源: 互联网

标签:transaction data 读写 分离 query Dapper null type public


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

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

IDapperPlusRead.cs

/// <summary>
    /// DapperPlus读接口
    /// </summary>
    public interface IDapperPlusRead
    {
        /// <summary>
        /// 连接
        /// </summary>
        public IDbConnection Connection
        {
            get;
        }
        /// <summary>
        /// Executes a single-row query, returning the data typed as type.
        /// </summary>
        /// <param name="type">The type to return.</param>
        /// <param name="sql">The SQL to execute for the query.</param>
        /// <param name="param">The parameters to pass, if any.</param>
        /// <param name="transaction">The transaction to use, if any.</param>
        /// <param name="buffered">Whether to buffer results in memory.</param>
        /// <param name="commandTimeout">The command timeout (in seconds).</param>
        /// <param name="commandType">The type of command to execute.</param>
        /// <returns>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.
        /// </returns>
        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

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

        /// <summary>
        /// Executes a single-row query, returning the data typed as type.
        /// </summary>
        /// <param name="type">The type to return.</param>
        /// <param name="sql">The SQL to execute for the query.</param>
        /// <param name="param">The parameters to pass, if any.</param>
        /// <param name="transaction">The transaction to use, if any.</param>
        /// <param name="buffered">Whether to buffer results in memory.</param>
        /// <param name="commandTimeout">The command timeout (in seconds).</param>
        /// <param name="commandType">The type of command to execute.</param>
        /// <returns>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.
        /// </returns>
        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

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

        /// <summary>
        /// Executes a single-row query, returning the data typed as type.
        /// </summary>
        /// <param name="type">The type to return.</param>
        /// <param name="sql">The SQL to execute for the query.</param>
        /// <param name="param">The parameters to pass, if any.</param>
        /// <param name="transaction">The transaction to use, if any.</param>
        /// <param name="buffered">Whether to buffer results in memory.</param>
        /// <param name="commandTimeout">The command timeout (in seconds).</param>
        /// <param name="commandType">The type of command to execute.</param>
        /// <returns>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.
        /// </returns>
        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<IDbConnection, MySqlConnection>();
     services.AddScoped<IDapperPlusRead, DapperPlusRead>();
     services.AddScoped<IDapperPlusWrite, DapperPlusWrite>();
}

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"
  }

 

  想要更快更方便的了解相关知识,可以关注微信公众号   

 

 

标签:transaction,data,读写,分离,query,Dapper,null,type,public
来源: https://www.cnblogs.com/axzxs2001/p/15864268.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有