• MSMQ消息队列的简单使用


    消息队列:微软提供的消息处理技术,用于解决高并发问题,减缓数据库压力。

    安装方式

    添加完功能之后,在计算机→管理→服务和应用程序 中可以看到消息队列

    当我们在程序中,可能会存在并发问题的时候,可以使用消息队列来解决高并发。

    工作原理,见贴:http://www.cnblogs.com/stopfalling/p/5375492.html

    简单示例:

     客户端代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Messaging;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MSMQConsumer
    {
        class Program
        {
            static void Main(string[] args)
            {
                MessageQueue MSMQ = CreateMessageQueue(@".private$	pmsmq");
                MSMQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
    
                Console.WriteLine("是否继续发送消息:Y/N?");
                string cmd = Console.ReadLine();
    
                while (cmd.Equals("Y"))
                {
                    Sender(MSMQ);
    
                    Console.WriteLine("是否继续发送消息:Y/N?");
                    cmd = Console.ReadLine();
                }
    
                Console.WriteLine("按任意键以停止...");
                Console.ReadKey();
            }
            private static void Sender(MessageQueue MSMQ)
            {
                try
                {
                    string random = GenerateRandom();
                    string obj = string.Format("{0} 发送方:{1}",
                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), random);
    
                    MSMQ.Send(obj, MessageQueueTransactionType.Single);
    
                    Console.WriteLine(obj);
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("{0} 发送方:{1}",
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.Message));
                }
            }
    
            public static MessageQueue CreateMessageQueue(string path)
            {
                MessageQueue mq = null;
    
                if (MessageQueue.Exists(path))
                {
                    mq = new MessageQueue(path);
                }
                else
                {
                    mq = MessageQueue.Create(path, true);
                }
    
                return mq;
            }
    
            public static string GenerateRandom()
            {
                int seed = GetRandomSeed();
                return new Random(seed)
                    .Next(Int32.MaxValue).ToString();
            }
    
            /// <summary>
            /// 创建加密随机数生成器 生成强随机种子
            /// </summary>
            /// <returns></returns>
            private static int GetRandomSeed()
            {
                byte[] bytes = new byte[4];
                System.Security.Cryptography.RNGCryptoServiceProvider rng
                    = new System.Security.Cryptography.RNGCryptoServiceProvider();
                rng.GetBytes(bytes);
                return BitConverter.ToInt32(bytes, 0);
            }
        }
    }
    View Code

    服务器端代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Messaging;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace MSMQProducer
    {
        class Program
        {
            static void Main(string[] args)
            {
                MessageQueue MSMQ = CreateMessageQueue(@".private$	pmsmq");
                MSMQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
    
                Receiver(MSMQ);
            }
    
            private static void Receiver(MessageQueue MSMQ)
            {
                while (true)
                {
                    try
                    {
                        Console.WriteLine("线程id:{0}",Thread.CurrentThread.ManagedThreadId);
                        Message m = MSMQ.Receive(MessageQueueTransactionType.Single);
                        Console.WriteLine(string.Format("{0} 接收方:[{1}]",
                            DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), m.Body.ToString()));
                        Console.WriteLine("线程id:{0}", Thread.CurrentThread.ManagedThreadId);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("{0} 接收方:{1}",
                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.Message));
                    }
                }
            }
    
            public static MessageQueue CreateMessageQueue(string path)
            {
                MessageQueue mq = null;
    
                if (MessageQueue.Exists(path))
                {
                    mq = new MessageQueue(path);
                }
                else
                {
                    mq = MessageQueue.Create(path, true);
                }
    
                return mq;
            }
        }
    
    }
    View Code
  • 相关阅读:
    Android Gradle Plugin指南(五)——Build Variants(构建变种版本号)
    文件内容操作篇clearerr fclose fdopen feof fflush fgetc fgets fileno fopen fputc fputs fread freopen fseek ftell fwrite getc getchar gets
    文件操作篇 close creat dup dup2 fcntl flock fsync lseek mkstemp open read sync write
    嵌入式linux应用程序调试方法
    version control system:git/hg/subversion/cvs/clearcase/vss。software configruation management。代码集成CI:Cruisecontrol/hudson/buildbot
    最值得你所关注的10个C语言开源项目
    如何记录linux终端下的操作日志
    CentOS 5.5 虚拟机安装 VirtualBox 客户端增强功能
    sizeof, strlen区别
    C/C++嵌入式开发面试题
  • 原文地址:https://www.cnblogs.com/scyr/p/9547937.html
Copyright © 2020-2023  润新知