让Dapper支持读写分离

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/302208.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php显示前60个字,DEDECMS中怎么让文章标题栏突破60个字符

DEDECMS中怎么让文章标题栏突破60个字符&#xff1f;1、使用PHPMYADMIN 修改 MYSQL数据结构CODE: ALTER TABLE dede_archives CHANGE title title VARCHAR( 250 ) [Copy to clipboard]2、打开/dede/action_article_save.php找到39行 CODE: $title cn_substr($title,60); [Copy…

数学是理工基础,如何才能令人信服?

随着科技的快速发展&#xff0c;人工智能的重要性日渐显现。而数学知识蕴含着处理智能问题的基本思想与方法&#xff0c;是理解复杂算法的必备要素。在机器学习工作流程中&#xff0c;数学与代码高度交织在一起&#xff0c;代码通常可以根据数学直观地构建&#xff0c;甚至会共…

GNU make manual 翻译(四十三)

继续翻译 Another such occasion is when you want to generate prerequisites from source files automatically; the prerequisites can be put in a file that is included by the main makefile. This practice is generally cleaner than that of somehow appending …

巧用定时任务监控第三方组件是否正常

背景平常我们系统一般会涉及到一些使用第三方组件的情况&#xff0c;那么我们如何去监测&#xff0c;第一时间知道组件是否可用。或者是组件没报错&#xff0c;但是没法返回我们想要的数据。问题窥探一般做法是在调用的时候&#xff0c;如果是异常&#xff0c;就发出对应的报警…

php调用另一个php文件里的变量的值,thinkphp中一个方法调用另一个步骤的变量

thinkphp中一个方法调用另一个方法的变量//实例化上传类public function upload() {$upload new Upload();$upload->maxSize 10 * 1024 * 1024;$upload->exts array(jpg, jpeg, gif, txt,zip);$upload->savePath ./;$upload->hash false;$info $upload->u…

Win7玩CF,不能全屏的解决方法...

今天用自己的本本玩CF&#xff0c;发天竟然不能全屏&#xff0c;抓狂呀&#xff01; 在网上找了下&#xff0c;解决方法如下: 打开注册表&#xff0c;定位到: HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\GraphicsDrivers\Configuration\AUO183C0_01_07D9_17^773484D7596…

EFCore之增删改查

1. 连接数据库通过依赖注入配置应用程序&#xff0c;通过startup类的ConfigureService方法中的AddDbContext将EFCore添加到依赖注入容器public void ConfigureServices(IServiceCollection services) {services.AddControllers();services.AddDbContext<OpenDbContext>(o…

matlab提示未定义wc,WooCommerce 教程:修复致命错误调用未定义的函数wc_get_order() - WooCommerce 微站...

我为客户开发了一个自定义支付网关插件&#xff0c;他们希望为 “鳕鱼”(货到付款)添加类似的方法。他希望增加一种称为 “交货卡” 的方法。我只是复制代码&#xff0c;将 PHP 添加到一个文件中&#xff0c;制作了一个插件&#xff0c;并给他插件 zip 文件。一切都很好&#x…

一堂儿童科学实验课引起的思考:数学和化学有什么关系?

全世界只有3.14 % 的人关注了数据与算法之美前段时间&#xff0c;我带侄子上了一堂化学课&#xff0c;回来之后&#xff0c;他一直意犹未尽找我的聊化学的事&#xff0c;期间他也问了身为数学专业的我一个交叉问题&#xff1a;叔&#xff0c;「数学」和「化学」有啥关系&#x…

自学网页设计

目前&#xff0c;我正在努力的学习网页设计&#xff0c;我是通过我要自学网http://www.51zxw.net/study.asp?vip5720219来学习的&#xff0c;还不错哦&#xff0c;加油!有时间大家也可以去看看&#xff0c;里面想学什么都可以找到的&#xff01;转载于:https://blog.51cto.com…

使用 KubernetesClient 操作 kubernetes

使用 KubernetesClient 操作 kubernetesIntro我们的应用都是部署在 Kubernetes 上的&#xff0c;我们有一个服务内部有一层 MemoryCache&#xff0c;之前会依赖 Redis 的 Pub/Sub 来做缓存的更新&#xff0c;而 Redis 的 Pub/Sub 是一种不可靠的更新机制&#xff0c;容易发生消…

cent os重置mysql,linux mysql 能登陆不能修改用户(cent os 6.2)解决思路

linux mysql 能登陆不能修改用户(cent os 6.2)[root3mao /]# select user,host,password from mysql.userbash: syntax error near unexpected token from[root3mao /]# mysql -u rootWelcome to the MySQL monitor. Commands end with ; or /g.Your MySQL connection id is 4S…

本、硕、博到底有什么区别?清华教授的“兔子理论”让你快速弄懂

全世界只有3.14 % 的人关注了数据与算法之美前段时间&#xff0c;有人问到卢sir一个问题——“本、硕、博之间到底有什么区别&#xff1f;”曾经就有一位清华大学教授就讨论过这个问题&#xff0c;让我们来看看这位清华教授是如何看待本、硕、博区别的吧。作者 | 阎学通教授清华…

迁移SVN注意事项及操作方法

最近公司要迁移SVN到新服务器&#xff0c;虽说现在GIT貌似更胜一筹&#xff0c;但是相信用svn的公司还是不在少数&#xff0c;就花了点时间把自己迁移的过程整理了一下。 文档中也许还有不足之处&#xff0c;有问题的话&#xff0c;大家可以告诉我&#xff0c;我会在第一时间修…

重磅!微软发布新一代 Teams 开发工具 —— Teams Toolkit!不止VS Code extension!

今天凌晨&#xff08;北京时间 2021 年 5 月 26 日&#xff09;&#xff0c;在一年一度的 Build 大会上&#xff0c;微软正式发布了新一代的 Teams 开发工具 —— Teams Toolkit。截止到 2021 年 4 月份&#xff0c;Microsoft Teams 的日活用户已经达到了惊人的1.45亿&#xff…

myclipes 配置php,myclipse使用技巧

myclipse内存清理 垃圾箱设置1.找到你的MyEclipse的工作空间。路径&#xff1a;MyEclipse\.metadata\.plugins\org.eclipse.core.runtime\.settings\2.用记事本或写字板打开org.eclipse.ui.prefs添加&#xff1a;SHOW_MEMORY_MONITORtrue3.重启MyEclipse&#xff0c;就会看到下…

UML实践----用例图、顺序图、状态图、类图、包图、协作图

http://www.uml.org.cn/oobject/200901203.asp UML实践----用例图、顺序图、状态图、类图、包图、协作图 2009-01-20 作者&#xff1a;Randy Miller 来源&#xff1a;网络 面向对象的问题的处理的关键是建模问题。建模可以把在复杂世界的许多重要的细节给抽象出。许多建模工具封…

“六级”题公布,觉得WebAPI简单的,勿进!

大型业务为什么需要深入WebAPI?众所周知&#xff0c;开发健壮的&#xff0c;稳定的&#xff0c;高度扩展性的业务程序&#xff0c;必须要有好的业务框架程序。就好比宝马X5和东风雪铁龙&#xff0c;如果大家体验过两车性能&#xff0c;都知道&#xff0c;宝马X5的性能甩东风雪…

oracle 有计划任务吗,oracle计划任务的问题

oracle计划任务的问题今天我尝试了一下oracle的job&#xff0c;做了个简单的应用&#xff0c;出现点问题想不明白&#xff0c;请求各位大大为我解惑.答案满意直接100分奉上写出我的步骤如下&#xff1a;1.创建job_test表&#xff0c;jobtest_sequence用于测试。表字段id number…

hdu 2896 病毒侵袭

http://acm.hdu.edu.cn/showproblem.php?pid2896 AC自动机的简单题。。。忘记关debug了&#xff0c;wa了一次。。。囧&#xff01; View Code 1 #include <cstdio>2 #include <cstring>3 #include <algorithm>4 #include <set>5 #include <cstdli…