EntityFramework6.0的Sql读写分离拦截器 和 MVC的 Action拦截器 对比
EF的DbCommandInterceptor类 拦截:
EF6.1也出来不少日子了,6.1相比6.0有个很大的特点就是新增了System.Data.Entity.Infrastructure.Interception 命名空间,此命名空间下的对象可以允许我们更加方便的了解到EF运行时的一些信息,当然我们最想看的还是EF生成的Sql语句,话不多讲,开始干吧;
class EFIntercepterLogging : DbCommandInterceptor
{
private readonly Stopwatch _stopwatch = new Stopwatch();
public override void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
base.ScalarExecuting(command, interceptionContext);
_stopwatch.Restart();
}
public override void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
_stopwatch.Stop();
if (interceptionContext.Exception != null)
{
Trace.TraceError("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
Trace.TraceInformation("\r\n执行时间:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", _stopwatch.ElapsedMilliseconds, command.CommandText);
}
base.ScalarExecuted(command, interceptionContext);
}
public override void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
base.NonQueryExecuting(command, interceptionContext);
_stopwatch.Restart();
}
public override void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
_stopwatch.Stop();
if (interceptionContext.Exception != null)
{
Trace.TraceError("Exception:{1} \r\n --> Error executing command:\r\n {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
Trace.TraceInformation("\r\n执行时间:{0} 毫秒\r\n-->NonQueryExecuted.Command:\r\n{1}", _stopwatch.ElapsedMilliseconds, command.CommandText);
}
base.NonQueryExecuted(command, interceptionContext);
}
public override void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
base.ReaderExecuting(command, interceptionContext);
_stopwatch.Restart();
}
public override void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
_stopwatch.Stop();
if (interceptionContext.Exception != null)
{
Trace.TraceError("Exception:{1} \r\n --> Error executing command:\r\n {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
Trace.TraceInformation("\r\n执行时间:{0} 毫秒 \r\n -->ReaderExecuted.Command:\r\n{1}", _stopwatch.ElapsedMilliseconds, command.CommandText);
}
base.ReaderExecuted(command, interceptionContext);
}
}
上面这段代码需要命名空间:
using System.Data.Entity.Infrastructure.Interception;
using System.Diagnostics;
从方法名我们可以看出大致就三类:读取类的sql,[Reader],非读取类的sql,[NonQuery],还有[Scalar],这类用的比较少,跟原始的ADO.NET命令类型基本一样,不多讲.每个sql语句类型的方法都有执行前Executing,执行后Executed,从命名上我们就可以看出AOP的身影哈,接下来看如何使用它...
嗯,对没错,就是这么简单,当然你还可以把红线里那句代码放在Global文件里.
我们看看运行效果
个人感觉是比用什么插件,第三方类库,SqlProfile什么的方便点点,用博客园的Google搜索了一下,貌似没发现其他园友写这个方法,可能是太简单了,都不愿意写,还是麻烦推荐一下让更多的园友看到!
-------
MVC拦截器:
MVC过滤器 OnActionExecuting() 在过滤器中获取触发控制器,Action 等
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing; namespace FB.CMS.MvcSite
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "FB.CMS.MvcSite.Areas.admin.Controllers" }//项目中如果存在多个Home控制器,需要设定Home控制器的名称空间 ).DataTokens.Add("area", "admin") //.DataTokens.Add("area","admin")就表示将区域里的admin区域的Home控制器的Index视图设为默认启动项
;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MVC过滤器.Filters
{
//自定义一个过滤器
[MyActionFilter]
public class MyActionFilterAttribute:ActionFilterAttribute
{
//重写OnActionExecuting方法
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//我们先来了解一下这个filterContext参数:我们知道OnActionExecuting方法是在Action执行之前会被触发执行的一个方法,那就意味着,将来我在这里面写代码,想要知道你这一个OnActionExecuting方法到底是由那一个Action被调用的时候触发的 (因为所有的action方法被执行的时候都会触发OnActionExecuting这个过滤器方法,所以我就像要知道到底是哪个action被执行的时候触发的这个OnActionExecuting方法) //获取触发当前方法(OnActionExecuting)的Action名字(即:哪个Action方法被执行的时候触发的OnActionExecuting(ActionExecutingContext filterContext))
string actionName = filterContext.ActionDescriptor.ActionName; //获取触发当前方法的的Action所在的控制器名字
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; //获取触发当前方法的Action方法的所有参数(因为参数可能有多个,所以它是一个集合,它的返回值类型是IDictionary<string ,object> 下面为了好看,用var替代)
var paramss = filterContext.ActionParameters; string str = "";
if (paramss.Any()) //Any是判断这个集合是否包含任何元素,如果包含元素返回true,否则返回false
{
foreach (var key in paramss.Keys) //遍历它的键;(因为我们要获取的是参数的名称s,所以遍历键)
{
str = key + "的值是" + paramss[key]; //paramss[key] 是key的值
}
} //获取当前请求的上下文
filterContext.HttpContext.Response.Write("你好,我也好"); //将触发当前方法的这个Action方法的返回结果视图换成一个JsonResult ( filterContext.Result的返回类型就是JsonResult) //filterContext.Result:获取或设置由操作方法返回的结果。(既然是获取或者设置Action方法的返回结果,那么我们就可以在这里篡改触发当前方法的那个Action方法的返回结果 //例如:触发当前方法的Action方法是这个:public ActionResult Add(){return Content("中国");} 这个Action方法的返回值是一个"中国"文本 那么我们在这里可以通过filterContext.Result来篡改它的返回值。比如这我给他返回一个json JsonResult json=new JsonResult();
json.Data=new { status="",message="OK"};
json.JsonRequestBehavior = JsonRequestBehavior.AllowGet; filterContext.Result = json; //假设我们在MVC项目中添加一个名字为admin的区域,然后再区域下添加一个Home控制器,然后添加一个Index视图。
//那现在我们访问这个视图的路径就是:http://localhost:5219/admin/home/index
//获取区域
var area = filterContext.RouteData.DataTokens;//MVC可以有区域的,这里就是负责存放区域的 //获取区域名称
var areaName = area["area"];//这个["area"]是写死了的。你根据["area"]就可以取到区域名称,因为区域的key固定就是area 所以这里areaName的值为admin //RouteData
var rd = filterContext.RouteData; //在这里面可以获取控制名称,ation名称,参数名称 var controlName = rd.Values["Controller"].ToString();
var actName = rd.Values["Action"].ToString(); }
}
}
EntityFramework6.0的Sql读写分离拦截器 和 MVC的 Action拦截器 对比的更多相关文章
- springboot2.0+mycat实验读写分离
声明:用户到达一定程度,架构就必须要考虑,因为在这个前提下,读写分离,尤为重要. 1.搭建mysql主从复制 https://www.cnblogs.com/ywjfx/p/10264383.html ...
- ASP.NET MVC的Action拦截器(过滤器)ActionFilter
有时项目要进行客户端请求(action)进行拦截(过滤)验证等业务,可以使用拦截器进行实现,所谓的action拦截器也没有什么的,只是写一个类,继承另一个类(System.Web.Mvc.Filter ...
- MVC 在action拦截器中获取当前进入的控制器和aciton名
我们在实现了action拦截器以后(继承至System.Web.Mvc.IActionFilter),需要在重写的方法OnActionExecuting中去获得当前进入的控制器和action名称,如何 ...
- ShardingSphere-proxy-5.0.0建立mysql读写分离的连接(六)
一.修改配置文件config-sharding.yaml,并重启服务 # # Licensed to the Apache Software Foundation (ASF) under one or ...
- EF架构~通过EF6的DbCommand拦截器来实现数据库读写分离~再续~添加对各只读服务器的心跳检测
回到目录 上一讲中基本实现了对数据库的读写分离,而在选择只读数据库上只是随机选择,并没有去检测数据库服务器是否有效,如服务器挂了,SQL服务停了,端口被封了等等,而本讲主要对以上功能进行一个实现,并对 ...
- Mycat实现读写分离,主备热切换
实验环境:ubutu server 14 Master IP:172.16.34.212 Slave IP:172.16.34.34.156 Mycat server IP:172.16.34.219 ...
- 基于Mycat实现读写分离
随着应用的访问量并发量的增加,应用读写分离是很有必要的.当然应用要实现读写分离,首先数据库层要先做到主从配置,本人前一篇文章介绍了mysql数据库的主从配置方式即:<mysql数据库主从配置&g ...
- mycat 安装 分表 分库 读写分离
简单的 理解 一下 mycat :如图 mycat 是一个 连接数据库的中介.一个独立安装的 工具,他连接着真实的数据库,并且 把自己伪装成一个数据库. 程序连接 mycat ,mycat 连接 到真 ...
- Mysql读写分离方案-MySQL Proxy环境部署记录
Mysql的读写分离可以使用MySQL Proxy和Amoeba实现,其实也可以使用MySQL-MMM实现读写分离的自动切换.MySQL Proxy有一项强大功能是实现"读写分离" ...
随机推荐
- jQuery自动加载更多程序
1.1.1 摘要 现在,我们经常使用的微博.微信或其他应用都有异步加载功能,简而言之,就是我们在刷微博或微信时,移动到界面的顶端或低端后程序通过异步的方式进行加载数据,这种方式加快了数据的加载速度,由 ...
- 知方可补不足~SqlServer连接的复用MultipleActiveResultSets
回到目录 MultipleActiveResultSets可以使数据库连接复用,但当你上了moebius这种集群工具后,这个选项不能开启(默认是false),当你使用EF等ORM工具时,这个选项会默认 ...
- PDO连接mysql和pgsql数据库
PDO连接mysql数据库 <?php $dsn="mysql:host=localhsot;dbname=lamp87"; $user="root"; ...
- 控制台屏蔽某console的输出
有时候需要调试一个在线网站. 打开 chrome 控制台,其中有一些 console.log 不停的输出. 这样的话就影响了我们使用控制台调试页面. 那么怎样不让那一句(或多句)console.log ...
- 据说,每一个 iOSer 都想要一张 Swift 大会门票
据说,每一个 iOSer 都想要一张中国首届 Swift 开发者大会的门票: 那么,福利来了-- fir.im 作为中国首届 Swift 大会的唯一钻石赞助商,有最后 2 张价值 600 多的门票(已 ...
- C++生成二级制文件过程(预处理->编译->链接 )
转载请注明出处 Windows下C++编程,通过VC生成工程,编写C++源文件,点运行,代码没问题直接出结果.VC什么都帮我们搞了,不了解其中过程也完全没问题. 转到linux下写c++,总觉得有点虚 ...
- javascript_basic_03之函数、循环、数组
1.函数:函数(Function),方法(Method),过程(Procedure): 2.默认为假的情况: ①if(0){}:②if(0.0){}:③if(null){}:④if("&qu ...
- SQL Server Window Function 窗体函数读书笔记二 - A Detailed Look at Window Functions
这一章主要是介绍 窗体中的 Aggregate 函数, Rank 函数, Distribution 函数以及 Offset 函数. Window Aggregate 函数 Window Aggrega ...
- maven -- 学习笔记(二)之setting.xml配置说明(备忘)
setting.xml配置说明,learn from:http://pengqb.javaeye.com,http://blog.csdn.net/mypop/article/details/6146 ...
- Lua 学习笔记(四)语句与控制结构
一.赋值与多重赋值 赋值的基本含义是改变一个变量的值或table中字段的值.Lua中允许“多重赋值”,也就是同时为多个值赋予多个变量,每个变量之间以逗号分隔. Lua会先对等号右边 ...