码迷,mamicode.com
首页 > 其他好文 > 详细

Redis分布式队列解决文件并发的问题

时间:2017-08-06 14:14:27      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:except   tostring   压力   ror   sleep   user   rom   分布式   rediscli   

1.首先将捕获的异常写到Redis的队列中

 1  public class MyExceptionAttribute : HandleErrorAttribute
 2     {
 3         public static IRedisClientsManager clientManager = new PooledRedisClientManager(new string[] { "127.0.0.1:6379", "192.168.1.2:6379" });
 4         public static IRedisClient redisClent = clientManager.GetClient();
 5         public override void  OnException(ExceptionContext filterContext)
 6         {
 7             base.OnException(filterContext);
 8             Exception ex = filterContext.Exception;
 9             //接下来就是得加入到队列中进行处理
10             redisClent.EnqueueItemOnList("errorMsg", ex.ToString());
11             //跳转到错误页面
12             filterContext.HttpContext.Response.Redirect("/Error.html");
13         }
14     }

2.然后单独开启一个线程对捕获的数据写到文件中去

  public void StartDealLog()
        {
            string filePath = Server.MapPath("/Log/");
            ThreadPool.QueueUserWorkItem((a) =>
            {
                while (true)
                {
                    if (MyExceptionAttribute.redisClent.GetListCount("errorMsg")>0)
                    {
                       // Exception ex = MyExceptionAttribute.MyExceptionQueue.Dequeue();
                        string ex=MyExceptionAttribute .redisClent.DequeueItemFromList("errorMsg");
                        if (ex != null)
                        { 
                           //将错误写到日志中取
                            ILog logger = LogManager.GetLogger("errorMsg");
                            logger.Error(ex);
                        }
                        else
                        {
                            Thread.Sleep(3000);
                        }
                    }
                    else
                    {//将当前线程挂起(就近)
                        Thread.Sleep(3000);
                    }
                }
            },filePath);
        }

3.关于上面的代码的思考

对于每一个错误,IIS所在的服务器都会启动一个线程,这对程序服务器压力还是很大的,所以可以考虑使用Redis的分布式,将上面的处理代码单独放到一台异常处理服务器上,可以是一个控制台程序或者网站程序,只要把上面的代码复制过去就可以了

Redis分布式队列解决文件并发的问题

标签:except   tostring   压力   ror   sleep   user   rom   分布式   rediscli   

原文地址:http://www.cnblogs.com/XZhao/p/7294479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!