コード例 #1
0
ファイル: MQConsumer.cs プロジェクト: belain/Utils
 /// <summary>
 /// 关闭消费者
 /// </summary>
 public static void CloseConsumer()
 {
     try
     {
         NLogHelper.Info("开始关闭MQ Consumer");
         if (session != null)
         {
             session.Dispose();
             session.Close();
         }
         session = null;
     }
     catch (Exception ex)
     {
         NLogHelper.Error("关闭MQ Session失败:" + ex);
     }
     try
     {
         if (connection != null)
         {
             connection.Stop();
             connection.Dispose();
             connection.Close();
         }
         connection = null;
     }
     catch (Exception ex)
     {
         NLogHelper.Error("关闭MQ连接失败:" + ex);
     }
 }
コード例 #2
0
        /// <summary>
        /// 消息处理的线程
        /// </summary>
        /// <param name="obj"></param>
        private static void MsgHandleCallback(object obj)
        {
            MessageItem item = null;

            while (isRunning)
            {
                if (RecvBlockingQueue.TryTake(out item, 1000))
                {
                    if (item == null || string.IsNullOrWhiteSpace(item.Message))
                    {
                        continue;
                    }

                    try
                    {
                        string message = item.Message.Trim();
                        NLogHelper.Info("开始处理消息:" + message);
                        //TODO: 处理消息

                        #region 处理消息


                        #endregion
                    }
                    catch (Exception ex)
                    {
                        NLogHelper.Info("处理消息失败:" + ex);
                    }
                }
            }
        }
コード例 #3
0
ファイル: MQConsumer.cs プロジェクト: belain/Utils
 /// <summary>
 /// init 消费者
 /// </summary>
 public static bool InitConsumer()
 {
     try
     {
         if (connection != null)
         {
             CloseConsumer();
         }
         NLogHelper.Info("开始初始化MQConsumer");
         //通过工厂构建链接
         connection = factory.CreateConnection();
         //设置连接的标识
         connection.ClientId                       = "HuiZhouDatagramPaser";
         connection.ExceptionListener             += connection_ExceptionListener;
         connection.ConnectionInterruptedListener += connection_ConnectionInterruptedListener;
         //启动连接
         connection.Start();
         //通过连接创建一个对话
         session = connection.CreateSession();
         //通过会话创建一个消费者
         IMessageConsumer consumer =
             session.CreateConsumer(new ActiveMQQueue(ConfigurationManager.AppSettings["MQName"]));
         //注册监听事件
         consumer.Listener += ConsumerOnListener;
         isAlive            = true;
         NLogHelper.Info("初始化MQConsumer成功,等待接收报文... ...");
         return(true);
     }
     catch (Exception ex)
     {
         NLogHelper.Error("初始化MQ失败:" + ex);
         return(false);
     }
 }
コード例 #4
0
        public static void EmployeeInsertForDingTalk(SqlSugarClient Edb, SqlSugarClient Ddb, List <V_EmployeeToDingTalk> ESB_EmployeeList)
        {
            NLogHelper log = NLogFactory.GetLogger("EmployeeInsertForDingTalk");
            List <V_OperationObject>    OperationList = new List <V_OperationObject>();
            List <V_EmployeeToDingTalk> EmpList       = new List <V_EmployeeToDingTalk>();

            OperationList = Tbiz_OperationTempBll.GetOperationList(Edb, 1, 1);
            List <V_EmployeeToDingTalk> EmployeeList = ESB_EmployeeList.Where(p => OperationList.Exists(q => q.UserId == p.UserId)).ToList();

            log.Info("\r\n------------------------------------------------ESB人员数据导入到钉钉------------------------------------------------\r\n");

            #region 循环插入到钉钉
            foreach (var item in EmployeeList)
            {
                if (item.Enabled == 1)
                {
                    InsertForDingTalk(Edb, Ddb, EmpList, item);
                }
                else
                {
                    DeleteForDingTalk(Ddb, EmpList, item);
                }
            }

            int d = 0;
            foreach (var item in EmpList)
            {
                d = Edb.Deleteable <Tbiz_OperationTemp>().Where(it => it.ObjectId.Equals(item.UserId)).ExecuteCommand();
            }
            #endregion
        }
コード例 #5
0
        /// <summary>
        /// 发送消息的线程
        /// </summary>
        /// <param name="obj"></param>
        private static void SendCallBack(object obj)
        {
            MessageItem item = null;

            while (IsRunning)
            {
                //阻塞1s
                if (SendBlockingQueue.TryTake(out item, 1000))
                {
                    if (item == null || string.IsNullOrWhiteSpace(item.Message))
                    {
                        //空消息
                        continue;
                    }

                    try
                    {
                        NLogHelper.Info("开始发送消息" + item.Message);
                        byte[] buffer = Encoding.GetEncoding(EncodingStr).GetBytes(item.Message);

                        int sendCount = socket.Send(buffer, 0, buffer.Length, SocketFlags.None);
                        lastSendRecvTime = DateTime.Now;
                        _isDisconnect    = false;
                    }
                    catch (Exception ex)
                    {
                        NLogHelper.Error("发送消息失败:" + ex);
                    }
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// 获取设备唯一id  32位 小写英文字母
        /// 此函数第1次调用耗时1-2秒
        /// </summary>
        /// <returns></returns>
        public static string UniqueDeviceId()
        {
            lock (locker)
            {
                if (!String.IsNullOrWhiteSpace(cacheDeviceId))
                {
                    return(cacheDeviceId);
                }
            }


            //bios是固化到主板的程序,有了主板id,可以忽略biosid
            //string deviceId = CpuId() + "_"+ BiosId() + "_" + DiskId() + "_" + MotherboardId();
            //现实中可能更换机器但不更换ip
            string deviceId = CpuId() + "_" + BiosId() + "_" + MotherboardId();

            NLogHelper.Info("DeviceId=" + deviceId);
            string tempDeviceId = GetMD5HashFromString(deviceId);

            lock (locker)
            {
                cacheDeviceId = tempDeviceId;
            }

            return(tempDeviceId);
        }
コード例 #7
0
        public void Intercept(IInvocation invocation)
        {
            var currentUserName = "******";

            //记录被拦截方法信息的日志信息
            var dataIntercept = "" +
                                $"【当前操作用户】:{currentUserName} \r\n" +
                                $"【当前执行方法】:{invocation.Method.Name} \r\n" +
                                $"【携带的参数有】:{string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())} \r\n";

            try
            {
                //在被拦截的方法执行完毕后 继续执行当前方法,注意是被拦截的是异步的
                invocation.Proceed();

                if (invocation.Method.IsAsyncMethod())
                {
                    var type           = invocation.Method.ReturnType;
                    var resultProperty = type.GetProperty("Result");
                    if (resultProperty != null)
                    {
                        dataIntercept +=
                            $"【执行完成结果】:{ Json.ToJson(resultProperty.GetValue(invocation.ReturnValue), true) }";
                    }

                    Parallel.For(0, 1, e =>
                    {
                        _logger.Info(dataIntercept);
                    });
                }
                else
                {
                    dataIntercept += $"【执行完成结果】:{ Json.ToJson(invocation.ReturnValue, true) }";
                    Parallel.For(0, 1, e =>
                    {
                        _logger.Info(dataIntercept);
                    });
                }
            }
            catch (Exception e)
            {
                _logger.Error("An exception occurs at LogAOP.cs", e);
                throw;
            }
        }
コード例 #8
0
 /// <summary>
 /// 列举表的索引
 /// </summary>
 /// <param name="table"></param>
 public static void ListIndex(IMongoCollection <BsonDocument> table)
 {
     using (var cursor = table.Indexes.List())
     {
         foreach (var indexItem in cursor.ToEnumerable())
         {
             NLogHelper.Info(indexItem.ToString());
         }
     }
 }
コード例 #9
0
 /// <summary>
 /// 列出所有的数据库
 /// </summary>
 public void ListDataBase()
 {
     using (var cursor = _client.ListDatabases())
     {
         foreach (BsonDocument document in cursor.ToEnumerable())
         {
             //{ "name" : "admin", "sizeOnDisk" : 32768.0, "empty" : false }
             NLogHelper.Info(document.ToString());
         }
     }
 }
コード例 #10
0
        /// <summary>
        /// 清理日志job
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IJobExecutionContext context)
        {
            lock (Slocker)
            {
                if (_isRunning)
                {
                    return;
                }
                _isRunning = true;
            }

            try
            {
                //开始时间
                DateTime startTime = DateTime.Now;
                //过期时间
                DateTime expireTime = DateTime.Now.Subtract(new TimeSpan(KeepDays, 0, 0, 0)).Date;

                #region 其它清理工作

                //清理sqlite中央日志

                CleanSqliteDb(expireTime);

                #endregion

                #region 清理日志文件工作

                //清理日志
                CleanLog(LogDir);

                #endregion

                //清理日志使用的时间
                DateTime endTime      = DateTime.Now;
                TimeSpan usedTimeSpan = endTime - startTime;
                NLogHelper.Info($"耗时{usedTimeSpan.TotalSeconds}秒----({usedTimeSpan})");
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"清理日志失败:{ex}");
            }
            finally
            {
                lock (Slocker)
                {
                    _isRunning = false;
                }
            }
        }
コード例 #11
0
        public static void Main(string[] args)
        {
            //红黑树
            SortedDictionary <string, string> rbTree = new SortedDictionary <string, string>();

            DirectoryHold.ResetCurrentDir();
            NLogHelper.Info(GuidUtils.GetGuid32());
            NLogHelper.Trace("Trace");
            NLogHelper.Debug("Debug");
            NLogHelper.Info("Info");
            NLogHelper.Warn("Warn");
            NLogHelper.Error("Error");
            NLogHelper.Fatal("Fatal");
        }
コード例 #12
0
 /// <summary>
 /// 发布启用·
 /// </summary>
 public static void ProducerStart()
 {
     NLogHelper.Info("开始启动Producer");
     connection       = factory.CreateConnection();
     session          = connection.CreateSession();
     responseProducer =
         session.CreateProducer(
             session.GetDestination(ConfigurationManager.AppSettings["ActivemqDestination"].Trim(),
                                    DestinationType.Topic));
     if (connection != null && !connection.IsStarted)
     {
         connection.Start();
         NLogHelper.Info("启动Producer成功");
     }
 }
コード例 #13
0
        /// <summary>
        /// 关闭消费者
        /// </summary>
        public static void CloseConsumer()
        {
            try
            {
                if (consumer != null)
                {
                    NLogHelper.Info("开始关闭MQ Consumer:" + MqUri);
                    consumer.Close();
                    consumer = null;
                }
            }
            catch (Exception ex)
            {
                NLogHelper.Error("关闭MQ Consumer失败:" + ex);
            }

            try
            {
                if (session != null)
                {
                    session.Close();
                    session = null;
                }
            }
            catch (Exception ex)
            {
                NLogHelper.Error("关闭MQ session失败:" + ex);
            }

            try
            {
                if (connection != null)
                {
                    connection.Stop();
                    connection.Close();
                    connection = null;
                }
            }
            catch (Exception ex)
            {
                NLogHelper.Error("关闭MQ连接connection失败:" + ex);
            }

            lock (locker)
            {
                _isAlive = false;
            }
        }
コード例 #14
0
        public ActionResult Index()
        {
            Trace.WriteLine("一般信息");
            Trace.TraceInformation("告知性信息");
            Trace.TraceWarning("警告信息");
            Trace.TraceError("错误信息");
            // NLogHelper.Debug("log信息");
            NLogHelper.Trace("Trace Message");
            NLogHelper.Debug("Debug Message");
            NLogHelper.Info("Info Message");
            NLogHelper.Error("Error Message");
            NLogHelper.Fatal("Fatal Message");
            IQueryable <User> user = _userService.Select(c => true);

            return(View(user));
        }
コード例 #15
0
 /// <summary>
 /// 关闭串口
 /// </summary>
 public void Stop()
 {
     try
     {
         isAlive = false;
         if (_serialPort != null)
         {
             _serialPort.Close();
             _serialPort = null;
             NLogHelper.Info("串口关闭成功");
         }
     }
     catch (Exception ex)
     {
         NLogHelper.Error($"关闭串口失败:{ex}");
     }
 }
コード例 #16
0
        /// <summary>
        /// 启动
        /// </summary>
        /// <returns></returns>
        public bool Start()
        {
            if (_serialPort != null)
            {
                Stop();
            }

            try
            {
                _serialPort           = new SerialPort(portName);//, 9600, Parity.None, 8, StopBits.One);
                _serialPort.BaudRate  = baudRate;
                _serialPort.Parity    = parity;
                _serialPort.StopBits  = stopBits;
                _serialPort.DataBits  = dataBits;
                _serialPort.Handshake = handshake;
                _serialPort.ReceivedBytesThreshold = receivedBytesThreshold;//
                _serialPort.DtrEnable    = dtrEnable;
                _serialPort.RtsEnable    = rtsEnable;
                _serialPort.ReadTimeout  = readWriteTimeout;
                _serialPort.WriteTimeout = readWriteTimeout;
                _serialPort.Encoding     = encoding;

                //数据接收事件
                _serialPort.DataReceived += SerialPortOnDataReceived;
                //端口出错事件
                _serialPort.ErrorReceived += SerialPortOnErrorReceived;
                //非数据信号事件
                _serialPort.PinChanged += SerialPort_PinChanged;
                //串口dispose事件
                _serialPort.Disposed += SerialPort_Disposed;

                _serialPort.Open();

                lastCommunicateTime = DateTime.Now;
                isAlive             = true;
                NLogHelper.Info($"打开串口{portName}成功");
                return(true);
            }
            catch (Exception ex)
            {
                NLogHelper.Error("打开串口失败:" + ex);

                isAlive = false;
                return(false);
            }
        }
コード例 #17
0
 private Func <int, Task> HandleMessageAsync(Question question)
 {
     _test.TestLog();
     return(async(id) =>
     {
         if (new Random().Next(0, 2) == 0)
         {
             Console.WriteLine("Exception Happened!!!!");
             NLogHelper.Info("Exception Happened!!!!" + "   " + question.Text);
             throw new Exception("Error Hanppened!" + "   " + question.Text);
         }
         else
         {
             NLogHelper.Info("BEGIN");
             Thread.Sleep(10000);
             Console.WriteLine(string.Format("worker:{0},content:{1}", id, question.Text));
             NLogHelper.Info(string.Format("worker:{0},content:{1}", id, question.Text));
         }
     });
 }
コード例 #18
0
        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="exceptionHandler"></param>
        /// <returns></returns>
        public static bool Start(Action <Exception> exceptionHandler = null)
        {
            try
            {
                Stop(exceptionHandler);

                //创建并打开连接
                _connection = SFactory.CreateConnection();

                //定义连接事件
                //连接阻塞的回调
                _connection.ConnectionBlocked += ConnectionOnConnectionBlocked;
                //连接未阻塞的回调
                _connection.ConnectionUnblocked += ConnectionOnConnectionUnblocked;
                //连接回调异常
                _connection.CallbackException += ConnectionOnCallbackException;
                //连接恢复错误
                _connection.ConnectionRecoveryError += ConnectionOnConnectionRecoveryError;
                //连接恢复成功
                _connection.RecoverySucceeded += ConnectionOnRecoverySucceeded;
                //连接关闭
                _connection.ConnectionShutdown += ConnectionOnConnectionShutdown;

                lock (SLocker)
                {
                    _isAlive = true;
                }
                NLogHelper.Info("mq启动完成");
                return(true);
            }
            catch (Exception e)
            {
                lock (SLocker)
                {
                    _isAlive = false;
                }
                exceptionHandler?.Invoke(e);

                return(false);
            }
        }
コード例 #19
0
 /// <summary>
 /// 发送字符串消息
 /// </summary>
 /// <param name="message"></param>
 public static void SendMessage(String message)
 {
     try
     {
         NLogHelper.Info("开始给航显发送消息:" + message);
         ProducerStart();
         if (responseProducer != null && session != null)
         {
             responseProducer.Send(session.CreateTextMessage(message));
         }
         NLogHelper.Info("发送消息成功");
     }
     catch (Exception ex)
     {
         NLogHelper.Error("发送给航显消息失败:" + ex);
     }
     finally
     {
         ProducerClose();
     }
 }
コード例 #20
0
        /// <summary>
        /// 注:该方法将定期按时执行,
        /// 意味着如果下一个周期到来,而上一次执行未完成,该方法开启一个新线程执行
        ///
        /// 在方法内部使用try/catch捕获所有异常
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;//获取job的数据

            Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "   " + DateTime.Now);

            lock (_locker)
            {
                if (_isRunning)
                {
                    return;
                }
                _isRunning = true;
            }

            string jobName = "";

            try
            {
                jobName = GetType().Name;

                NLogHelper.Info($"开始执行任务{jobName}");

                //调用实际的任务
                ActualJobCallback();

                NLogHelper.Info($"结束执行任务{jobName}");
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"执行任务{jobName}异常:" + ex);
            }
            finally
            {
                lock (_locker)
                {
                    _isRunning = false;
                }
            }
        }
コード例 #21
0
        /// <summary>
        /// 解析字符列表
        /// </summary>
        /// <param name="readList"></param>
        private void ParseBytes(List <byte> readList)
        {
            if (readList == null || readList.Count == 0)
            {
                return;
            }

            #region 实际的解析消息

            String s = Encoding.UTF8.GetString(readList.ToArray());
            NLogHelper.Info(s);
            readList.Clear();

            #endregion


            if (readList.Count >= MaxBufferSizeBeforeAbandon)
            {
                //超出数据,清空
                readList.Clear();
            }
        }
コード例 #22
0
        /// <summary>
        /// 开始连接
        /// </summary>
        public static void Start()
        {
            try
            {
                Stop();

                NLogHelper.Info("开始建立到{0}:{1}的连接".FormatWith(serverIp, serverPort));

                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                socket.SendTimeout = socket.ReceiveTimeout = SendRecvTimeout;

                socket.Connect(IPAddress.Parse(serverIp), serverPort);
                lastSendRecvTime = DateTime.Now;
                _isDisconnect    = false;
                //初始化接收\发送多线程
                InitThread();
            }
            catch (Exception ex)
            {
                NLogHelper.Error("连接失败:" + ex);
                Stop();
            }
        }
コード例 #23
0
        public static bool AddEmployee(SqlSugarClient Edb, SqlSugarClient Ddb, V_EmployeeToDingTalk item)
        {
            bool       result = true;
            NLogHelper log    = NLogFactory.GetLogger("AddEmployee");

            try
            {
                EmployeeEntity model           = new EmployeeEntity();
                string         DD_DepartmentId = "1";
                if (!item.ESB_DepartmentId.Equals("1000000001"))
                {
                    DepartmentResult DD_DepModel = Ddb.Queryable <DepartmentResult>().With(SqlWith.NoLock).Where(it => it.ESB_DepartmentID.Equals(item.ESB_DepartmentId)).First();
                    if (DD_DepModel == null)
                    {
                        DD_DepartmentId = DepartmentForDingTalkBll.DD_DepartmentIsNullForDingTalk(Edb, Ddb, item.ESB_DepartmentId);
                    }
                    else
                    {
                        DD_DepartmentId = DD_DepModel.id;
                    }
                }

                model.userid     = item.UserId;
                model.name       = item.Name;
                model.department = new List <int>(new int[] { Convert.ToInt32(DD_DepartmentId) });
                model.position   = item.PositionName;
                model.mobile     = item.Mobile;
                model.tel        = item.Telephone;
                model.workPlace  = "";
                model.remark     = "";
                model.email      = item.Email;
                model.jobnumber  = item.UserId;
                model.isSenior   = false;

                string param = JsonConvert.SerializeObject(model);

                EmployeeResult Result = EmployeeBll.Create(param);
                if (Result != null)
                {
                    if (Result.errcode == "0")
                    {
                        //Console.Write("创建成功,UserId=" + Result.userid);
                    }
                    //该外部联系人已存在 ||	手机号码在公司中已存在
                    else if (Result.errcode == "40026" || Result.errcode == "60104")
                    {
                        string res = EmployeeBll.Delete(model.userid).errcode;
                        if (res != "0")
                        {
                            log.Error("\r\n EmployeeForDingTalkBll-AddEmployee() 手机号码在公司中已存在删除时报错,错误编号:" + res);
                        }
                        EmployeeResult Result2 = EmployeeBll.Create(JsonConvert.SerializeObject(model));
                        if (Result2.errcode != "0")
                        {
                            if (Result2.errcode == "40022")
                            {
                                string Deletecode = EmployeeBll.Delete(model.userid).errcode;

                                string Createcode = EmployeeBll.Create(JsonConvert.SerializeObject(model)).errcode;

                                if (Createcode != "0")
                                {
                                    Createcode = EmployeeBll.Create(JsonConvert.SerializeObject(model)).errcode;
                                    if (Createcode != "0" && Createcode != "40021")
                                    {
                                        log.Error("\r\n AddEmployee - 行号507 成功删除员工信息,但是创建员工信息时报错,错误编码如下:" + Createcode);
                                        result = false;
                                    }
                                }
                                //手机号码在公司中已存在
                                if (Result2.errcode == "60104")
                                {
                                    log.Debug("\r\n EmployeeForDingTalkBll-AddEmployee() 手机号码在公司中已存在 时报错,信息如下" + Result2.errmsg + ",错误编码为:" + Result2.errcode + ", Json参数为:" + param);
                                }
                                else
                                {
                                    log.Error("\r\n EmployeeForDingTalkBll-AddEmployee() 该外部联系人已存在 ||	手机号码在公司中已存在 时报错,信息如下"+ Result2.errmsg + ",错误编码为:" + Result2.errcode + ", Json参数为:" + param);
                                    result = false;
                                }

                                Task.Factory.StartNew(() =>
                                {
                                    InsertErroUpdateEmployee(model.userid, "", item.Mobile, Result.errcode);
                                    if (Deletecode != "0")
                                    {
                                        InsertErroUpdateEmployee(model.userid, "", item.Mobile, "新增用户时,删除失败,错误编号:" + Deletecode);
                                    }
                                    if (Createcode != "0")
                                    {
                                        InsertErroUpdateEmployee(model.userid, "", item.Mobile, "新增用户时,执行删除后创建失败,错误编号:" + Createcode);
                                    }
                                });
                            }
                            else
                            {
                                log.Error("\r\n EmployeeForDingTalkBll-AddEmployee() " + Result.errmsg + ",错误编码为:" + Result.errcode);
                                result = false;
                            }
                        }
                    }
                    else
                    {
                        if (Result.errcode == "60103")
                        {
                            log.Debug("\r\n EmployeeForDingTalkBll-AddEmployee() " + Result.errmsg + ",错误编码为:" + Result.errcode + ",手机号为" + item.Mobile + ",用户id为" + item.UserId + " Json参数为:" + param);
                            result = true;
                        }
                        //UserID在公司中已存在
                        else if (Result.errcode == "60102")
                        {
                            log.Info("\r\n EmployeeForDingTalkBll-AddEmployee() " + Result.errmsg + ",错误编码为:" + Result.errcode);
                            result = true;
                        }
                        else
                        {
                            log.Error("\r\n EmployeeForDingTalkBll-AddEmployee() " + Result.errmsg + ",错误编码为:" + Result.errcode);
                            result = false;
                        }

                        Task.Factory.StartNew(() =>
                        {
                            InsertErroUpdateEmployee(model.userid, "", item.Mobile, "新增用户时创建失败," + Result.errmsg + ",错误编号:" + Result.errcode);
                        });
                    }
                }
                else
                {
                    result = false;
                }
            }
            catch (Exception ex)
            {
                result = false;
                log.Error("\r\n EmployeeForDingTalkBll-AddEmployee() " + ex + "\r\n");
            }
            return(result);
        }
コード例 #24
0
        public static void EmployeeUpdateForDingTalk(SqlSugarClient Edb, SqlSugarClient Ddb, List <V_EmployeeToDingTalk> ESB_EmployeeList)
        {
            NLogHelper log = NLogFactory.GetLogger("EmployeeUpdateForDingTalk");
            List <V_EmployeeToDingTalk> EmpList = new List <V_EmployeeToDingTalk>();
            //获取ESB中目前已经更新的数据
            List <V_OperationObject> OperationList = Tbiz_OperationTempBll.GetOperationList(Edb, 1, 0);
            //根据ESB操作记录中更新的ID,查出目前的用户信息
            List <V_EmployeeToDingTalk> EmployeeList = ESB_EmployeeList.Where(p => OperationList.Exists(q => q.UserId == p.UserId)).ToList();

            log.Info("\r\n------------------------------------------------根据ESB更新钉钉中的人员信息------------------------------------------------\r\n");

            #region 循环更新到钉钉
            foreach (var item in EmployeeList)
            {
                if (item.Enabled == 1)
                {
                    string EmployeeJson = GetEmployee(item.UserId);
                    //用户ID在钉钉中不存在,即:离职用户重新录用时,应将该用户重新添加进钉钉
                    if (EmployeeJson.Equals("-1"))
                    {
                        AddEmployee(Edb, Ddb, item);
                        EmpList.Add(item);
                        continue;
                    }
                    else
                    {
                        EmployeeEntity   model           = Newtonsoft.Json.JsonConvert.DeserializeObject <EmployeeEntity>(EmployeeJson);
                        string           oldMobile       = model.mobile;
                        string           DD_DepartmentId = "1";
                        DepartmentResult DD_DepModel     = Ddb.Queryable <DepartmentResult>().With(SqlWith.NoLock).Where(it => it.ESB_DepartmentID.Equals(item.ESB_DepartmentId)).First();
                        if (DD_DepModel == null)
                        {
                            try
                            {
                                DD_DepartmentId = DepartmentForDingTalkBll.DD_DepartmentIsNullForDingTalk(Edb, Ddb, item.ESB_DepartmentId);
                            }
                            catch (Exception ex)
                            {
                                DD_DepartmentId = DepartmentForDingTalkBll.DD_DepartmentIsNullForDingTalk(Edb, Ddb, item.ESB_DepartmentId);
                            }
                        }
                        else
                        {
                            DD_DepartmentId = DD_DepModel.id;
                        }
                        model.userid     = item.UserId;
                        model.name       = item.Name;
                        model.department = new List <int>(new int[] { Convert.ToInt32(DD_DepartmentId) });
                        model.position   = item.PositionName;
                        model.mobile     = item.Mobile;
                        model.tel        = item.Telephone;
                        model.email      = item.Email;
                        model.jobnumber  = item.UserId;
                        string param = JsonConvert.SerializeObject(model);

                        Result Result = EmployeeBll.Update(param);
                        if (Result != null)
                        {
                            if (Result.errcode == "0")
                            {
                                EmpList.Add(item);
                                //Console.Write("更新成功," + Result.errmsg);
                            }
                            else
                            {
                                //UserID不存在
                                if (Result.errcode == "60111")
                                {
                                    AddEmployee(Edb, Ddb, item);
                                    EmpList.Add(item);
                                    continue;
                                }
                                //更新手机号出错时
                                else if (Result.errcode == "40022" || Result.errcode == "40021" || Result.errcode == "60104" || Result.errcode == "60121")
                                {
                                    //40021	更换的号码已注册过钉钉,无法使用该号码
                                    //40022 企业中的手机号码和登陆钉钉的手机号码不一致,暂时不支持修改用户信息,可以删除后重新添加
                                    //60104	手机号码在公司中已存在
                                    //60121	找不到该用户

                                    string Deletecode = EmployeeBll.Delete(model.userid).errcode;

                                    string Createcode = EmployeeBll.Create(JsonConvert.SerializeObject(model)).errcode;

                                    if (Createcode != "0")
                                    {
                                        Createcode = EmployeeBll.Create(JsonConvert.SerializeObject(model)).errcode;
                                        if (Createcode != "0" && Createcode != "40021")
                                        {
                                            log.Error("\r\n EmployeeUpdateForDingTalk - 行号135 更新钉钉人员信息时,成功删除员工信息,但是创建员工信息时报错,错误编码如下:" + Createcode + ", 员工编号为:" + model.userid);
                                        }
                                    }

                                    EmpList.Add(item);

                                    Task.Factory.StartNew(() =>
                                    {
                                        InsertErroUpdateEmployee(model.userid, oldMobile, item.Mobile, Result.errcode);
                                        if (Deletecode != "0")
                                        {
                                            InsertErroUpdateEmployee(model.userid, oldMobile, item.Mobile, "删除失败,错误编号:" + Deletecode);
                                        }
                                        if (Createcode != "0")
                                        {
                                            InsertErroUpdateEmployee(model.userid, oldMobile, item.Mobile, "执行删除后创建失败,错误编号:" + Createcode);
                                        }
                                    });

                                    //Console.Write("更新成功\r\n");
                                }
                                else
                                {
                                    //手机号码不合法
                                    if (Result.errcode == "60103")
                                    {
                                        model.mobile = oldMobile;
                                        Result       = EmployeeBll.Update(JsonConvert.SerializeObject(model));
                                        if (Result.errcode == "0")
                                        {
                                            EmpList.Add(item);
                                        }
                                        else
                                        {
                                            log.Error("\r\n EmployeeForDingTalkBll-EmployeeUpdateForDingTalk() 失败后不更新手机号,还是失败,具体信息: " + Result.errmsg + "; UserId=" + item.UserId);
                                        }
                                    }
                                    //部门在钉钉中不存在的时候
                                    else if (Result.errcode == "60003")
                                    {
                                        model.department = new List <int>(new int[] { 1 });

                                        param = JsonConvert.SerializeObject(model);

                                        Result r = EmployeeBll.Update(param);
                                        if (r.errcode == "0")
                                        {
                                            EmpList.Add(item);
                                        }
                                        else if (r.errcode == "40022" || r.errcode == "40021" || r.errcode == "60104" || r.errcode == "60121")
                                        {
                                            //40021	更换的号码已注册过钉钉,无法使用该号码
                                            //40022 企业中的手机号码和登陆钉钉的手机号码不一致,暂时不支持修改用户信息,可以删除后重新添加
                                            //60104	手机号码在公司中已存在
                                            //60121	找不到该用户

                                            string Deletecode = EmployeeBll.Delete(model.userid).errcode;

                                            string Createcode = EmployeeBll.Create(JsonConvert.SerializeObject(model)).errcode;

                                            if (Createcode != "0")
                                            {
                                                Createcode = EmployeeBll.Create(JsonConvert.SerializeObject(model)).errcode;
                                                if (Createcode != "0" && Createcode != "40021")
                                                {
                                                    log.Error("\r\n EmployeeUpdateForDingTalk - 行号199 更新钉钉人员信息时,成功删除员工信息,但是创建员工信息时报错,错误编码如下:" + Createcode);
                                                }
                                            }

                                            EmpList.Add(item);

                                            Task.Factory.StartNew(() =>
                                            {
                                                InsertErroUpdateEmployee(model.userid, oldMobile, item.Mobile, r.errcode);
                                                if (Deletecode != "0")
                                                {
                                                    InsertErroUpdateEmployee(model.userid, oldMobile, item.Mobile, "删除失败,错误编号:" + Deletecode);
                                                }
                                                if (Createcode != "0")
                                                {
                                                    InsertErroUpdateEmployee(model.userid, oldMobile, item.Mobile, "执行删除后创建失败,错误编号:" + Createcode);
                                                }
                                            });

                                            //Console.Write("更新成功\r\n");
                                        }
                                        else
                                        {
                                            log.Debug("\r\n EmployeeForDingTalkBll-EmployeeUpdateForDingTalk() 钉钉中部,部门id=" + DD_DepartmentId + ",已将该人员挂在公司下," + Result.errmsg + "; UserId=" + item.UserId);

                                            Task.Factory.StartNew(() =>
                                            {
                                                InsertErroUpdateEmployee(model.userid, oldMobile, item.Mobile, "更新用户时失败,错误编号:" + Result.errcode);
                                            });
                                        }
                                    }
                                    else
                                    {
                                        log.Error("\r\n EmployeeForDingTalkBll-EmployeeUpdateForDingTalk() " + Result.errmsg + "; UserId=" + item.UserId);

                                        Task.Factory.StartNew(() =>
                                        {
                                            InsertErroUpdateEmployee(model.userid, oldMobile, item.Mobile, "更新用户时失败,错误编号:" + Result.errcode);
                                        });
                                    }
                                }
                            }
                        }
                        else
                        {
                            //Console.Write("无返回数据");
                        }
                    }
                }
                else
                {
                    Result Result = EmployeeBll.Delete(item.UserId);
                    if (Result != null)
                    {
                        //找不到该用户
                        if (Result.errcode == "0" || Result.errcode == "60121")
                        {
                            EmpList.Add(item);
                            //Console.Write("删除成功," + Result.errmsg + "\r\n");
                        }
                        else
                        {
                            log.Error("\r\n EmployeeForDingTalkBll-EmployeeUpdateForDingTalk() " + Result.errmsg + "; UserId=" + item.UserId);
                            //Console.Write("\r\n" + Result.errmsg + "; UserId=" + item.UserId);
                        }
                    }
                    else
                    {
                        //Console.Write("无返回数据");
                    }
                }
            }
            int d = 0;
            foreach (var item in EmpList)
            {
                d = Edb.Deleteable <Tbiz_OperationTemp>().Where(it => it.ObjectId.Equals(item.UserId)).ExecuteCommand();
            }
            #endregion
        }
コード例 #25
0
        /// <summary>
        /// 初始化消息处理线程
        /// </summary>
        public static void Init()
        {
            lock (MessageQueue)
            {
                if (_messageHandlerThread != null)
                {
                    return;
                }

                //设置为运行
                _isRunning = true;
            }



            _messageHandlerThread = new Thread(() =>
            {
                while (_isRunning)
                {
                    try
                    {
                        int curCount = MessageQueue.Count;

                        if (curCount > ThresholdCanBeListHandled)
                        {
                            int batchSize = ThresholdCanBeListHandled;
                            if (curCount > MaxBatchSize)
                            {
                                batchSize = MaxBatchSize;
                            }

                            List <CommonMessage> msgList = new List <CommonMessage>(batchSize);

                            CommonMessage message = null;
                            for (int i = 0; i < batchSize; i++)
                            {
                                if (MessageQueue.TryTake(out message))
                                {
                                    msgList.Add(message);
                                }
                                else
                                {
                                    break;
                                }
                            }


                            try
                            {
                                HandleListMessage(msgList);
                            }
                            catch (Exception ex)
                            {
                                NLogHelper.Error("HandleListMessage处理消息失败,异常信息:" + ex);
                            }
                        }
                        else
                        {
                            CommonMessage message = null;
                            //等待517ms获取消息
                            if (MessageQueue.TryTake(out message, 517))
                            {
                                #region 处理消息message

                                try
                                {
                                    HandleMessage(message);
                                }
                                catch (Exception ex)
                                {
                                    NLogHelper.Error("HandleMessage处理消息失败,异常信息:" + ex);
                                }

                                #endregion
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        NLogHelper.Error("处理消息失败,异常信息:" + ex);
                    }
                }
            });

            //后台线程
            _messageHandlerThread.IsBackground = true;
            //消息优先级
            _messageHandlerThread.Priority = ThreadPriority.Normal;

            _messageHandlerThread.Start();

            NLogHelper.Info("初始化消息处理线程成功");

            return;
        }
コード例 #26
0
        /// <summary>
        /// 清理日志
        /// </summary>
        public void CleanLog(string logDirToClean)
        {
            NLogHelper.Info("开始清理日志");
            DirectoryInfo dirInfo = new DirectoryInfo(logDirToClean);

            if (!dirInfo.Exists)
            {
                NLogHelper.Warn($"未找到{logDirToClean}日志目录,无法清理");
                return;
            }


            DateTime expireTime = DateTime.Now.Subtract(new TimeSpan(KeepDays, 0, 0, 0)).Date;//过期时间

            #region 根据当前硬盘减少保存时间
            try
            {
                if (KeepDays > KeepDaysWhenAvailableLimit)
                {
                    DriveInfo driveInfo = null;

                    foreach (DriveInfo item in DriveInfo.GetDrives())
                    {
                        if (StringUtils.EqualsEx(dirInfo.Root.Name, item.RootDirectory.Name))
                        {
                            //查找logs所在的磁盘
                            driveInfo = item;
                            break;
                        }
                    }

                    //如果磁盘空间不足,保留更少的天数
                    if (driveInfo != null && driveInfo.AvailableFreeSpace < driveInfo.TotalSize * DriveAvailableLimit)
                    {
                        //当到达硬盘利用极限时,保存的天数
                        expireTime = DateTime.Now.Subtract(new TimeSpan(KeepDaysWhenAvailableLimit, 0, 0, 0)).Date;
                    }
                }
            }
            catch (Exception ex)
            {
                //ignore
                NLogHelper.Warn($"根据硬盘当前容量判断过期时间失败:{ex}");
            }
            #endregion


            NLogHelper.Info($"清理{expireTime.ToString("yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture)}之前的{dirInfo.FullName}目录的日志");

            //清理文件
            try
            {
                int delCount = CleanFiles(logDirToClean, SearchPatternArr, expireTime, currentDepth: 0);
                NLogHelper.Info($"共删除{delCount}个文件");
            }
            catch (Exception ex)
            {
                NLogHelper.Warn($"清理文件失败:{ex}");
            }

            try
            {
                //清理空目录
                int delCount = CleanEmptyDirectory(logDirToClean, currentDepth: 0);
                NLogHelper.Info($"共删除{delCount}个目录");
            }
            catch (Exception ex)
            {
                NLogHelper.Warn($"清理空目录失败:{ex}");
            }


            NLogHelper.Info("清理日志完成");
        }
コード例 #27
0
    private void ProcessRequest(NetworkStream inputStream)
    {
        var buffer         = new byte[1024 * 1024];
        var byteBag        = new List <byte>();
        var delimiterBytes = Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine);
        var count          = int.MaxValue;
        var index          = -1;

        do
        {
            count = 0;
            SystemHelper.InvokeSilently(delegate { count = inputStream.Read(buffer, 0, buffer.Length); });
            if (count > 0)
            {
                var buffer1 = buffer.Take(count).ToArray();
                index = buffer1.IndexOf(delimiterBytes);
                if (index == -1)
                {
                    byteBag.AddRange(buffer1);
                    NLogHelper.Info(Encoding.UTF8.GetString(byteBag.ToArray()));
                }
                else
                {
                    byteBag.AddRange(buffer1.Take(index));
                    var command     = Encoding.UTF8.GetString(byteBag.ToArray());
                    var headerBytes = buffer1.Skip(index + delimiterBytes.Length).ToArray();
                    NLogHelper.Info(command.Replace(delimiter, " "));
                    if (string.Equals(command, "list"))
                    {
                        var bytes = Encoding.UTF8.GetBytes(string.Join("|", from l in new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).GetFiles() select l.Name));
                        inputStream.Write(bytes, 0, bytes.Length);
                    }
                    else if (command.StartsWith("put"))
                    {
                        var commandStrings = command.Split(new[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
                        var fileName       = commandStrings[1];
                        var chunk          = int.Parse(commandStrings[2]);
                        var offset         = int.Parse(commandStrings[3]);
                        var length         = int.Parse(commandStrings[4]);
                        var fileInfo       = new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}{fileName}-{chunk}.temp");
                        using (var fileStream = !fileInfo.Exists ? fileInfo.Create() : File.OpenWrite(fileInfo.FullName))
                        {
                            fileStream.Seek(offset, SeekOrigin.Begin);
                            length -= headerBytes.Length;
                            fileStream.Write(headerBytes, 0, headerBytes.Length);
                            do
                            {
                                count   = inputStream.Read(buffer, 0, buffer.Length);
                                length -= count;
                                fileStream.Write(buffer, 0, count);
                            } while (length > 0 && count > 0);
                        }
                    }
                    else if (command.StartsWith("get"))
                    {
                        var commandStrings = command.Split(new[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
                        var fileName       = commandStrings[1];
                        var offset         = int.Parse(commandStrings[2]);
                        var length         = int.Parse(commandStrings[3]);
                        var fileInfo       = new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}{fileName}");
                        if (fileInfo.Exists)
                        {
                            using (var fileStream = File.OpenRead(fileInfo.FullName))
                            {
                                fileStream.Seek(offset, SeekOrigin.Begin);
                                do
                                {
                                    count = fileStream.Read(buffer, 0, buffer.Length);
                                    inputStream.Write(buffer, 0, Math.Min(count, length));
                                    length -= count;
                                }while (length > 0 && count > 0);
                            }
                        }
                    }
                    else if (command.StartsWith("length"))
                    {
                        var commandStrings = command.Split(new[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
                        var fileName       = commandStrings[1];
                        var chunk          = commandStrings[2];
                        var fileInfo       = chunk == "-1" ? new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}{fileName}") : new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}{fileName}-{chunk}.temp");
                        var length         = fileInfo.Exists ? fileInfo.Length : 0;
                        var bytes          = UTF8Encoding.UTF8.GetBytes(length.ToString());
                        inputStream.Write(bytes, 0, bytes.Length);
                    }
                    else if (command.StartsWith("splice"))
                    {
                        var commandStrings = command.Split(new[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
                        var fileName       = commandStrings[1];
                        var chunk          = int.Parse(commandStrings[2]);
                        var fileInfo       = new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}{fileName}");
                        using (var fileStream = !fileInfo.Exists ? fileInfo.Create() : File.OpenWrite(fileInfo.FullName))
                        {
                            var offset = 0;
                            for (var i = 1; i < chunk + 1; i++)
                            {
                                fileStream.Seek(offset, SeekOrigin.Begin);
                                var tempFile = new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}{fileName}-{i}.temp");
                                if (tempFile.Exists)
                                {
                                    using (var tempStream = File.OpenRead(tempFile.FullName))
                                    {
                                        count   = tempStream.Read(buffer, 0, buffer.Length);
                                        offset += count;
                                        fileStream.Write(buffer, 0, count);
                                    }

                                    tempFile.Delete();
                                }
                            }
                        }
                    }
                }
            }
        }while (count != 0 && index == -1);
    }
コード例 #28
0
        /// <summary>
        /// 初始化消费者
        /// </summary>
        /// <returns></returns>
        public static bool InitConsumer()
        {
            try
            {
                lock (locker)
                {
                    CloseConsumer();
                }

                NLogHelper.Info("开始初始化MQConsumer");

                //通过工厂构建连接
                //connection = (Connection)factory.CreateConnection();
                //如果使用了failover, CreateConnection如果连接不上将会阻塞
                connection = factory.CreateConnection();

                //默认是不支持事务,自动确认的
                //connection.AcknowledgementMode = AcknowledgementMode.AutoAcknowledge;
                //设置唯一的客户端ID
                connection.ClientId                       = Guid.NewGuid().ToString("N");
                connection.ExceptionListener             += connection_ExceptionListener;
                connection.ConnectionInterruptedListener += connection_ConnectionInterruptedListener;
                connection.ConnectionResumedListener     += ConnectionOnConnectionResumedListener;

                //connection.RedeliveryPolicy;//重发策略
                //超时16s
                connection.RequestTimeout = new TimeSpan(0, 0, 30);

                if (!connection.IsStarted)
                {
                    //启动连接 如果加了failover,不抛异常
                    connection.Start();
                }
                //创建回话
                session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                session.RequestTimeout = new TimeSpan(0, 0, 30);
                NLogHelper.Info("建立名为{0}的{1}连接".FormatWith(TopicOrQueueName, IsTopic ? "Topic" : "Queue"));
                //创建消费者  如果是主题,非持久订阅,断线后消息会丢失,即使消息是持久的且没有过期
                consumer = session.CreateConsumer(session.GetDestination(TopicOrQueueName, (IsTopic?DestinationType.Topic:DestinationType.Queue)));

                //创建持久订阅
                //session.CreateDurableConsumer
                //注册监听事件
                consumer.Listener += consumer_Listener;

                //最近一次通信时间
                _lastUpdateTime = DateTime.Now;

                NLogHelper.Info("MQ初始化成功");
                lock (locker)
                {
                    _isAlive = true;
                }
                return(true);
            }
            catch (Exception ex)
            {
                lock (locker)
                {
                    _isAlive = false;
                }

                NLogHelper.Error("MQ初始化失败:" + ex);
                return(false);
            }
        }
コード例 #29
0
        /// <summary>
        /// 消费者使用的Exchange的名字
        /// </summary>
        //private static readonly string UsedExchangeName = ConfigUtils.GetString("UsedExchangeName");

        /// <summary>
        /// 使用的RoutingKey
        /// </summary>
        //private static readonly string UsedRoutingKeyName = ConfigUtils.GetString("UsedRoutingKey");


        #endregion

        #region 启动Consumer

        /// <summary>
        /// 开启消费者
        /// </summary>
        /// <param name="exceptionHandler"></param>
        /// <returns></returns>
        public static bool StartConsumer(Action <Exception> exceptionHandler = null)
        {
            try
            {
                StopConsumer();

                //创建并打开连接
                _connection = SFactory.CreateConnection();

                //定义连接事件
                //连接阻塞的回调
                _connection.ConnectionBlocked += ConnectionOnConnectionBlocked;
                //连接未阻塞的回调
                _connection.ConnectionUnblocked += ConnectionOnConnectionUnblocked;
                //连接回调异常
                _connection.CallbackException += ConnectionOnCallbackException;
                //连接恢复错误
                _connection.ConnectionRecoveryError += ConnectionOnConnectionRecoveryError;
                //连接恢复成功
                _connection.RecoverySucceeded += ConnectionOnRecoverySucceeded;
                //连接关闭
                //closed: the object has received all shutdown-complete notification(s) from any lower-layer objects, and as a consequence has shut itself down
                //Those objects always end up in the closed state, regardless of the reason that caused the closure, like an application request, an internal client library failure, a remote network request or network failure.
                //连接一旦进入closed状态,将不会改变
                _connection.ConnectionShutdown += ConnectionOnConnectionShutdown;


                //创建多路复用的channel
                _channel = _connection.CreateModel();

                //if (_isQueue)
                //{
                //    // 1、创建exchange
                //    //使用direct
                //    //exchange:exchange的名字,//type:exchange的类型
                //    //durable - true if we are declaring a durable exchange (the exchange will survive a server restart)
                //    //autoDelete - true if the server should delete the exchange when it is no longer in use
                //    //arguments - other properties (construction arguments) for the exchange
                //    _channel.ExchangeDeclare(exchange: UsedExchangeName, type: ExchangeType.Direct, durable: true, autoDelete: false, arguments: null);

                //    //定义创建队列时的参数
                //    Dictionary<string, object> dictArgs = new Dictionary<string, object>();
                //    //限制队列的最大长度,超过该长度将从队列头丢弃
                //    dictArgs.Add("x-max-length",9000);


                //    //队列
                //    //queue:队列名
                //    //durable:true if we are declaring a durable queue (the 队列 will survive a server restart) 当mq重启后队列是否仍然存在
                //    //exclusive:排他性,如果为true,表示队列只能被当前连接使用,连接关闭队列自动消失
                //    //autoDelete:当已经没有消费者时,服务器是否可以删除该队列,true if the server should delete the queue when it is no longer in use。
                //   //队列创建时会默认绑定到default的direct的""的exchange
                //    _channel.QueueDeclare(queue: UsedQueueName, durable: true, exclusive: false, autoDelete: false,arguments: null);

                //    //建立queue和exchange的绑定
                //    _channel.QueueBind(queue: UsedQueueName, exchange: UsedExchangeName, routingKey: UsedRoutingKeyName, arguments: null);

                //    //prefetchSize - maximum amount of content (measured in octets) that the server will deliver, 0 if unlimited
                //    //prefetchCount - maximum number of messages that the server will deliver, 0 if unlimited
                //    //global - true if the settings should be applied to the entire channel rather than each consumer
                //    //每次取一个消息,消息大小不限制
                //    //注释掉该行,将会使用Robbin轮盘分配,使用下面这行,只有空闲的Consumer接收消息
                //    //我们设置prefetchCount=1,则Queue每次给每个消费者发送一条消息;消费者处理完这条消息后Queue会再给该消费者发送一条消息。
                //    _channel.BasicQos(prefetchSize:0,prefetchCount:3,global:false);

                //    //定义消息接收事件
                //    EventingBasicConsumer consumer = new EventingBasicConsumer(_channel);
                //    consumer.Received += ConsumerOnReceived;

                //    //自动应答
                //    _channel.BasicConsume(queue:UsedQueueName, autoAck:true, consumer:consumer);


                //    //同步调用
                //    //BasicGetResult getResult = _channel.BasicGet(queue:_usedDirectQueueName, autoAck: true);
                //    //if(getResult == null)
                //    //{
                //    //    //没有消息
                //    //}
                //    //else
                //    //{
                //    //    byte[] bodys = getResult.Body;
                //    //}
                //}
                //else
                //{
                //    // 1、创建exchange
                //    //使用fanout
                //    //exchange:exchange的名字,//type:exchange的类型
                //    //durable - true if we are declaring a durable exchange (the exchange will survive a server restart)
                //    //autoDelete - true if the server should delete the exchange when it is no longer in use
                //    //arguments - other properties (construction arguments) for the exchange
                //    _channel.ExchangeDeclare(exchange:UsedExchangeName,type:ExchangeType.Fanout,durable:true,autoDelete:false,arguments:null);

                //    //2、创建queue
                //    //由MQ服务器创建一个amp.开头的(如amq.gen-JzTY20BRgKO-HjmUJj0wLg)非持久、排他、自动删除的队列
                //    //连接断开后,服务器将删除该队列
                //    string tempQueueName = _channel.QueueDeclare().QueueName;

                //    //3、绑定queue
                //    //将队列绑定到exchange
                //    //fanout的routingkey不起作用,将会被忽略
                //    //使用指定的Routingkey将指定的queue绑定到指定的exchange上
                //    //如果关心多种消息,一个channel可以创建多个bind,可以使用相同的队列名(一个队列关心多个routingKey)
                //    _channel.QueueBind(queue:tempQueueName,exchange:UsedExchangeName,routingKey:"",arguments:null);

                //    //预取3条消息
                //    _channel.BasicQos(prefetchSize: 0, prefetchCount: 3, global: false);

                //    //定义消息接收事件
                //    EventingBasicConsumer consumer = new EventingBasicConsumer(_channel);
                //    consumer.Received += ConsumerOnReceived;

                //    //自动应答
                //    _channel.BasicConsume(queue: tempQueueName, autoAck: true, consumer: consumer);
                //}


                //每次取一个消息,消息大小不限制
                //注释掉该行,将会使用Robbin轮盘分配,使用下面这行,只有空闲的Consumer接收消息
                //我们设置prefetchCount=1,则Queue每次给每个消费者发送一条消息;消费者处理完这条消息后Queue会再给该消费者发送一条消息。
                _channel.BasicQos(prefetchSize: 0, prefetchCount: 5, global: false);

                //定义消息接收事件
                EventingBasicConsumer consumer = new EventingBasicConsumer(_channel);
                consumer.Received += ConsumerOnReceived;

                //自动应答
                _channel.BasicConsume(queue: UsedQueueName, autoAck: true, consumer: consumer);


                lock (SLocker)
                {
                    _isAlive = true;
                }
                NLogHelper.Info($"启动mq完成");
                return(true);
            }
            catch (Exception e)
            {
                lock (SLocker)
                {
                    _isAlive = false;
                }
                exceptionHandler?.Invoke(e);
                return(false);
            }
        }
コード例 #30
0
        /// <summary>
        /// 初始化消息处理线程
        /// </summary>
        public static void Init()
        {
            lock (messageQueue)
            {
                if (messageHandlerThread != null)
                {
                    return;
                }

                //设置为运行
                isRunning = true;
            }



            messageHandlerThread = new Thread(() =>
            {
                while (isRunning)
                {
                    try
                    {
                        String message = null;
                        //等待1111ms获取消息
                        if (messageQueue.TryTake(out message, 1111))
                        {
                            #region 处理消息message

                            try
                            {
                                HandleMessage(message);
                            }
                            catch (Exception ex)
                            {
                                NLogHelper.Error("HandleMessage处理消息失败,异常信息:" + ex);
                            }

                            #endregion
                        }
                    }
                    catch (Exception ex)
                    {
                        NLogHelper.Error("处理消息失败,异常信息:" + ex);
                        try
                        {
                            Thread.Sleep(5);
                        }
                        catch (Exception)
                        {
                            //ignore
                        }
                    }
                }
            });


            messageHandlerThread.Start();

            NLogHelper.Info("初始化消息处理线程成功");

            return;
        }