美文网首页.NET
rabbitmq c# 入门代码

rabbitmq c# 入门代码

作者: 事在人为s | 来源:发表于2020-04-14 14:42 被阅读0次

    1、新建2个控制台项目

    image

    2、生产者代码

    class Program
        { static void Main(string[] args)
            {
                ConnectionFactory factory = new ConnectionFactory()
                {
                    HostName = "127.0.0.1",
                    UserName = "guest",
                    Password = "guest",
                }; //第一步:创建connection
                var connection = factory.CreateConnection(); //第二步:创建一个channel
                var channel = connection.CreateModel(); //第三步:申明交换机【因为rabbitmq已经有了自定义的ampq default exchange】 //第四步:创建一个队列(queue)
                channel.QueueDeclare("mytest", true, false, false, null); var msg = Encoding.UTF8.GetBytes("你好"); //第五步:发布消息
                channel.BasicPublish(string.Empty, routingKey: "mytest", basicProperties: null, body: msg);
                Console.ReadKey();
            }
        }
    

    3、消费者代码

    class Program
        {
            static void Main(string[] args)
            {
                ConnectionFactory factory = new ConnectionFactory()
                {
                    HostName = "127.0.0.1",
                    UserName = "guest",
                    Password = "guest",
                };
    
                //第一步:创建connection
                var connection = factory.CreateConnection();
    
                //第二步:创建一个channel
                var channel = connection.CreateModel();
    
                //第三步:申明交换机【因为rabbitmq已经有了自定义的ampq default exchange】
    
                //第四步:获取消息
                var result = channel.BasicGet("mytest", true);
    
                var msg = Encoding.UTF8.GetString(result.Body);
    
                Console.WriteLine(msg);
    
                Console.ReadKey();
            }
        }
    

    相关文章

      网友评论

        本文标题:rabbitmq c# 入门代码

        本文链接:https://www.haomeiwen.com/subject/ptftvhtx.html