在上一篇说了封装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个方法}

DapperPlusWrite.cs

    /// <summary>/// 写Dapper类/// </summary>public class DapperPlusWrite : IDapperPlusWrite{private readonly IDbConnection _connection;/// <summary>/// 构造/// </summary>/// <param name="connection">连接</param>/// <param name="configuration">配置</param>public DapperPlusWrite(IDbConnection connection, IConfiguration configuration){var connectionStrings = configuration.GetSection("ConnectionStrings").Get<Dictionary<string, string>>();_connection = connection;_connection.ConnectionString = connectionStrings.Where(s => s.Key.ToLower().Contains("write")).FirstOrDefault().Value;}/// <summary>/// 连接/// </summary>public IDbConnection Connection{get{return _connection;}}/// <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>public int Execute(string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null){return _connection.Execute(sql, param, transaction, commandTimeout, commandType);}/// <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"}

让Dapper支持读写分离相关推荐

  1. 关于Dapper实现读写分离的个人思考

    概念相关 为了确保多线上环境数据库的稳定性和可用性,大部分情况下都使用了双机热备的技术.一般是一个主库+一个从库或者多个从库的结构,从库的数据来自于主库的同步.在此基础上我们可以通过数据库反向代理工具 ...

  2. EF通用数据层封装类(支持读写分离,一主多从)

    浅谈orm 记得四年前在学校第一次接触到 Ling to Sql,那时候瞬间发现不用手写sql语句是多么的方便,后面慢慢的接触了许多orm框架,像 EF,Dapper,Hibernate,Servic ...

  3. 阿里面试,为什么Kafka不支持读写分离

    转载自  阿里面试,为什么Kafka不支持读写分离 为什么数据库.redis都支持了读写分离功能,而kafka却没有? 厮大也是狠人,直接打开源码从头开始讲,我一看这情况不对,按照这进度得讲到天黑了, ...

  4. asp.net mysql 读写分离_[ASP.net教程]SqlSugar ORM已经支持读写分离

    [ASP.net教程]SqlSugar ORM已经支持读写分离 0 2016-11-26 23:00:12 目前只有MYSQL版 3.5.2.9 支持,其库版本12月3号更新该功能 用例讲解using ...

  5. Sharding-JDBC 1.3.0发布——支持读写分离

    当当的分布式数据库中间层Sharding-JDBC正式开源.经过近半年的潜心打磨,Sharding-JDBC于六一前夕正式发布1.3.0里程碑版本. Sharding-JDBC源于当当应用框架ddfr ...

  6. 干货|为什么Kafka不支持读写分离

    在 Kafka 中,生产者写入消息.消费者读取消息的操作都是与 leader 副本进行交互的,从 而实现的是一种主写主读的生产消费模型.数据库.Redis 等都具备主写主读的功能,与此同时还支持主写从 ...

  7. .NETCore 下支持分表分库、读写分离的通用 Repository

    首先声明这篇文章不是标题党,我说的这个类库是 FreeSql.Repository,它作为扩展库现实了通用仓储层功能,接口规范参数 abp vnext,定义和实现基础的仓储层(CURD). 安装 do ...

  8. day09_读写分离_组件介绍

    mysql中间件研究(Mysql-prxoy,Atlas,阿米巴,cobar,TDDL) mysql-proxy MySQL Proxy就是这么一个中间层代理,简单的说,MySQL Proxy就是一个 ...

  9. RDS读写分离,海量数据一键搞定

    (文末有彩蛋) 简介 RDS为用户提供高透明,高可用,高性能,高灵活的读写分离服务.在最近的版本我们基于短连接的用户进行了优化,使得短连接的用户负载均衡更加完善合理.RDS读写分离有如下特性: 易用/ ...

最新文章

  1. matlab在命令行注册,命令行运行matlab
  2. 10分钟!构建支持10万/秒请求的大型网站
  3. [Python爬虫] 在Windows下安装PIP+Phantomjs+Selenium
  4. protobuf入门教程(六):导入定义(import)
  5. html中如何让图片交错,HTML5/Canvas 光圈交错幻觉
  6. java 模拟登陆 post_Java开发网 - 高手帮忙啊 (如何用java模拟post方式进行登陆论坛?)...
  7. IAR执行到断点处不能单步运行解决方法
  8. matlab有限差分法编程波导_有限差分法的Matlab程序
  9. Spring-boot-AnnotationConfigServletWebApplicationContext
  10. 第 18 章 访问者模式
  11. oracle默认的优化器,Oracle优化器相关参数设置
  12. 第23章 排序算法(包括merge等)
  13. JSONKit去警告
  14. 从0到1:饿了么大数据平台Hadoop集群规模突破1000+之炼金术
  15. 【常用Dos命令操作】操作+图(1)
  16. 手把手教你写专利申请书/如何申请专利
  17. Latex中的特殊符号
  18. Unity游戏快速制作特效
  19. 图片CenterCrop和圆角问题(Glide加载)
  20. 基于闪电连接过程优化算法的函数寻优算法

热门文章

  1. 6月,回忆我失去的爱情
  2. 常用数据库连接和diriver以及默认端口
  3. 4-8 string
  4. 前后台分离--概念相关
  5. IPC之——消息队列
  6. linux守护进程的编写
  7. 【Tomcat】Tomcat配置与优化(内存、并发、管理)【自己配置】
  8. Git Bash的一些命令和配置
  9. jQuery 表单选择器
  10. CGRect vs CGPoint vs CGSize