基本版本 Queue

代码:

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace Rongzi.BZone.Admin.Functions
{
public class MyExceptionFilterAttribute : System.Web.Mvc.HandleErrorAttribute
{
//版本1:使用预置队列类型存储异常对象
public static Queue<Exception> ExceptionQueue = new Queue<Exception>(); public override void OnException(ExceptionContext filterContext)
{
//将异常信息入队
ExceptionQueue.Enqueue(filterContext.Exception);
//跳转到自定义错误页
filterContext.HttpContext.Response.Redirect("~/Common/CommonError.html"); base.OnException(filterContext);
}
}
}
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Rongzi.BZone.Admin.Functions; namespace Rongzi.BZone.Admin
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute()); // MyExceptionFilterAttribute继承自HandleError,主要作用是将异常信息写入日志文件中
filters.Add(new MyExceptionFilterAttribute());
//filters.Add(new CustomHandleExceptionAttribute(GetError));
} //public static string GetError(System.Exception ex)
//{
// ResponseContext result = new ResponseContext();
// result.Head.Ret = -1;
// result.Head.Code = ErrCode.ParameterError;
// var ret = JsonConvert.SerializeObject(result);
// return ret;
//}
}
}

Global

添加配置

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Net.Http.Formatting;
using Rongzi.BZone.Admin.Functions; namespace Rongzi.BZone.Admin
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
log4net.Config.XmlConfigurator.Configure(
new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\log4net.config")); MessageQueueConfig.RegisterExceptionLogQueue();
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//GlobalConfiguration.Configuration.EnableCors();
log4net.Config.XmlConfigurator.Configure();
var jsonFormatter = new JsonMediaTypeFormatter();
//GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
GlobalConfiguration.Configuration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
GlobalConfiguration.Configuration.MessageHandlers.Add(new ResponseDelegatingHandler());
}
}
}

对消息进行处理

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Text;
using System.IO; namespace Rongzi.BZone.Admin.Functions
{
public class MessageQueueConfig
{
public static void RegisterExceptionLogQueue()
{
string logFilePath = HttpContext.Current.Server.MapPath("/App_Data/");
//通过线程池开启线程,不停地从队列中获取异常信息并将其写入日志文件
ThreadPool.QueueUserWorkItem(o =>
{
while (true)
{
try
{
if (MyExceptionFilterAttribute.ExceptionQueue.Count > )
{
Exception ex = MyExceptionFilterAttribute.ExceptionQueue.Dequeue(); //从队列中出队,获取异常对象
if (ex != null)
{
//构建完整的日志文件名
string logFileName = logFilePath + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
//获得异常堆栈信息
string exceptionMsg = ex.ToString();
//将异常信息写入日志文件中
File.AppendAllText(logFileName, exceptionMsg, Encoding.Default);
}
}
else
{
Thread.Sleep(); //为避免CPU空转,在队列为空时休息1秒
}
}
catch (Exception ex)
{
MyExceptionFilterAttribute.ExceptionQueue.Enqueue(ex);
}
}
}, logFilePath);
}
}
}

Redis消息队列版本

对上面的进行修改

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServiceStack.Redis;
using System.Configuration;
using ServiceStack.Redis.Generic;
using Rongzi.BZone.Common.Util; namespace Rongzi.BZone.Admin.Functions
{
public class MyExceptionFilterAttribute : System.Web.Mvc.HandleErrorAttribute
{
//版本2:使用Redis的客户端管理器(对象池)
public IRedisClient redisClient = RedisCommon.getInstance.getRedisClient(); public override void OnException(ExceptionContext filterContext)
{
//将异常信息入队
redisClient.EnqueueItemOnList("ExceptionLog", filterContext.Exception.ToString());
//跳转到自定义错误页
filterContext.HttpContext.Response.Redirect("~/Common/CommonError.html"); base.OnException(filterContext);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Text;
using System.IO;
using ServiceStack.Redis;
using System.Configuration;
using ServiceStack.Redis.Generic;
using Rongzi.BZone.Common.Util; namespace Rongzi.BZone.Admin.Functions
{
public class MessageQueueConfig
{
public static IRedisClient redisClient = RedisCommon.getInstance.getRedisClient();
public static void RegisterExceptionLogQueue()
{
//通过线程池开启线程,不停地从队列中获取异常信息并将其写入日志文件
ThreadPool.QueueUserWorkItem(o =>
{
while (true)
{
try
{
if (redisClient.GetListCount("ExceptionLog") > )
{
//从队列中出队,获取异常对象
string errorMsg = redisClient.DequeueItemFromList("ExceptionLog");
if (!string.IsNullOrEmpty(errorMsg))
{
//使用Log4Net写入异常日志
LogHelper.Error(errorMsg);
}
}
else
{
Thread.Sleep(); //为避免CPU空转,在队列为空时休息1秒
}
}
catch (Exception ex)
{
redisClient.EnqueueItemOnList("ExceptionLog", ex.ToString());
}
}
});
}
}
}

http://www.tuicool.com/articles/Ubeyay3

消息队列MQ的更多相关文章

  1. 为什么会需要消息队列(MQ)?

    为什么会需要消息队列(MQ)? #################################################################################### ...

  2. 消息队列一:为什么需要消息队列(MQ)?

    为什么会需要消息队列(MQ)? #################################################################################### ...

  3. 详解RPC远程调用和消息队列MQ的区别

    PC(Remote Procedure Call)远程过程调用,主要解决远程通信间的问题,不需要了解底层网络的通信机制. RPC框架 知名度较高的有Thrift(FB的).dubbo(阿里的). RP ...

  4. 消息队列 MQ 入门理解

    功能特性: 应用场景: 消息队列 MQ 可应用于如下几个场景: 分布式事务 在传统的事务处理中,多个系统之间的交互耦合到一个事务中,响应时间长,影响系统可用性.引入分布式事务消息,交易系统和消息队列之 ...

  5. 消息队列MQ简介

    项目中要用到RabbitMQ,领导让我先了解一下.在之前的公司中,用到过消息队列MQ,阿里的那款RocketMQ,当时公司也做了简单的技术分享,自己也看了一些博客.自己在有道云笔记上,做了一些整理,但 ...

  6. 消息队列MQ集合

    消息队列MQ集合 消息队列简介 kafka简介 Centos7部署zookeeper和Kafka集群 .

  7. 高并发系统:消息队列MQ

    注:前提是知道什么是消息队列.不懂的去搜索各种消息队列入门(activeMQ.rabbitMQ.rocketMQ.kafka) 1.为什么要使用MQ?(MQ的好处:解耦.异步.削峰) (1)解耦:主要 ...

  8. java面试记录三:hashmap、hashtable、concurrentHashmap、ArrayList、linkedList、linkedHashmap、Object类的12个成员方法、消息队列MQ的种类

    口述题 1.HashMap的原理?(数组+单向链表.put.get.size方法) 非线程安全:(1)hash冲突:多线程某一时刻同时操作hashmap并执行put操作时,可能会产两个key的hash ...

  9. 【消息队列MQ】各类MQ比较

    目录(?)[-] RabbitMQ Redis ZeroMQ ActiveMQ JafkaKafka 目前业界有很多MQ产品,我们作如下对比: RabbitMQ 是使用Erlang编写的一个开源的消息 ...

  10. 消息队列mq的原理及实现方法

    消息队列技术是分布式应用间交换信息的一种技术.消息队列可驻留在内存或磁盘上,队列存储消息直到它们被应用程序读走.通过消息队列,应用程序可独立地执行--它们不需要知道彼此的位置.或在继续执行前不需要等待 ...

随机推荐

  1. C里面的类型字节长度和范围

    32位平台 char 1个字节8位 short 2个字节16位 int 4个字节32位 long 4个字节 long long 8个字节 指针 4个字节 64位平台 char 1个字节 short 2 ...

  2. HDU 2594 Simpsons’ Hidden Talents(KMP的Next数组应用)

    Simpsons’ Hidden Talents Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java ...

  3. 2016.04.27,英语,《Vocabulary Builder》Unit 19

    bio, comes from the Greek word for 'life'. biosphere ['baɪoʊsfɪr] n. 生物圈: biology [baɪ'ɑːlədʒi] n. 生 ...

  4. MySQL DATE_FORMAT() 函数

    定义和用法 DATE_FORMAT() 函数用于以不同的格式显示日期/时间数据. 语法 DATE_FORMAT(date,format) date 参数是合法的日期.format 规定日期/时间的输出 ...

  5. memory_limit session.cache_expire ecshop初始化注释说明

    memory_limit session.cache_expire ecshop初始化注释说明 memory_limit = 128M; 一个脚本所能够申请到的最大内存字节数(可以使用K和M作为单位) ...

  6. ArcMap 标注、注记、图形文本

    标注.注记.图形文本 2016年8月10日10:29 ArcMap中怎样向地图添加文本,其中标注与注记是重点内容,此处对此进行总结. 参考链接: ①地图文本基本词汇: 什么是文本? ArcGIS 提供 ...

  7. delphi 向其他程序发送模拟按键

    向其他程序发送模拟按键: 1.用keybd_event: varh : THandle;beginh := FindWindow('TFitForm', '1stOpt - [Untitled1]') ...

  8. MySql解决插入中文乱码问题

    在dos中登陆mysql 后输入: // 查看数据使用的所有编码show variables like 'character%';// 修改客户端的编码 为 gbkset character_set_ ...

  9. java 操作数据库

    package foo;import java.sql.*; public class JdbcDemo { private static Connection conn; private stati ...

  10. 地图API使用文档-以腾讯地图为例

    目录 腾讯地图API 2 1.API概览... 2 1.1 WebService API(官网注明是beta版本,可能不稳定,慎用):... 2 1.2 URL API:... 2 1.3 静态图AP ...