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有一项强大功能是实现"读写分离" ...
随机推荐
- 译文---C#堆VS栈(Part Four)
前言 在本系列的第一篇文章<C#堆栈对比(Part Three)>中,介绍了值类型和引用类型在Copy上的区别以及如何实现引用类型的克隆以及使用ICloneable接口等内容. 本文为文章 ...
- 使用ruby过程中遇到安装gem失败的一些通用解决方案
ruby语言升级还是比较勤快的.但是数量众多的版本使得程序库的兼容性成了大问题.有些gem表示明确不支持某个特定版本以前的ruby,而有些gem则与较高的版本不兼容.再加上gem本身也有版本,简直是乱 ...
- JITCompiler、NGen.exe及.NET Native
一.JITCompiler 如你所知,JIT(just-in-time或“即时”)编译器是CLR的重要组件,它的职责是将IL转换成本地cpu指令. <<CLR via C#>> ...
- java指定路径写、读文件
package com.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; ...
- WindowManager 实现悬浮窗 详解
WindowManager 实现悬浮窗 详解 一:对于想直接看效果的,可以看看我的demo app. 链接:http://sj.qq.com/myapp/detail.htm?apkName=com. ...
- Android开发学习之路-SimpleAdapter源码分析学习
今天在课堂上,老师用到了SimpleAdapter,然后女神在边上问我为什么这个SimpleAdapter不能做到我app那种带有进度条的效果,言语说不清,然后就开始看源代码,发现这个Adapter的 ...
- vs如何在C++中调用Lua
最近Cocos2dx的学习卡壳了,一般的照抄代码我不想写上来,但想示例也想得我头晕...为了放松大脑调整状态于是开始学习Lua.Lua的语法学习还是比较简单的,学过javascript或者vbscri ...
- fir.im Weekly - 可能是 iOS 审核最全面的解决方案
ipv6 被拒绝,后台定位被拒绝--让很多国内 iOS 开发者心力交瘁.这是一份关于 iOS 审核的终极免费方案,作者iOSWang对最近iOS 审核被拒问题给出了比较全面的方案:Solve-App- ...
- 设置easyui input默认值
/*设置input 焦点*/ $(function () { //集体调用 $(".formTextBoxes input").each(function () { $(this) ...
- 简明 Git 命令速查表
本文总结了git常用的命令,以便学习者使用时查阅~ 几个专用名词的译名如下 Workspace:工作区 Index / Stage:暂存区 Repository:仓库区(或本地仓库) Remote ...