Erlang 环境
需要配置 Er 语言环境。
下载
ttps://www.erlang.org/downloads
配置
windows 环境变量的 path 中添加 erlang 的 bin 文件夹。
RabbitMQ
下载
windows 安装包:https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.10.1/rabbitmq-server-3.10.1.exe
配置
- windows 环境变量的 path 中添加 rabbitmq 的 sbin 文件夹。
- 执行
rabbitmq-plugins enable rabbitmq_management
。
- 添加用户
rabbitmqctl add_user [username] [password]
。
- 为用户配置权限
rabbitmqctl set_user_tags [username] administrator
。
- 访问管理后台 http://localhost:15672,账号:guest,密码:guest。
- 后台中配置用户权限:Admin - 点击用户名 - Set permission。
使用
创建 2 个 ASP.NET 项目。分别是生产端和消费端。
生产端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| using RabbitMQ.Client; using System; using System.Text;
namespace MQProducer { class Program { private static void Main(string[] args) { Console.WriteLine("生产者"); IConnectionFactory factory = new ConnectionFactory { HostName = "172.21.46.105", Port = 5672, UserName = "rabbit1", Password = "rabbit1" }; IConnection con = factory.CreateConnection(); IModel channel = con.CreateModel();
string name = "demo"; channel.QueueDeclare( queue: name, durable: false, exclusive: false, autoDelete: false, arguments: null);
string str = string.Empty;
do { Console.WriteLine("发送内容:"); str = Console.ReadLine(); byte[] body = Encoding.UTF8.GetBytes(str); channel.BasicPublish("", name, null, body); Console.WriteLine("成功发送消息:" + str); } while (str.Trim().ToLower() != "exit");
con.Close(); channel.Close(); } } }
|
消费端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text;
namespace MQConsumer { internal class Program { private static void Main(string[] args) { Console.WriteLine("消费者"); IConnectionFactory factory = new ConnectionFactory { HostName = "172.21.46.105", Port = 5672, UserName = "rabbit1", Password = "rabbit1" };
IConnection conn = factory.CreateConnection(); IModel channel = conn.CreateModel(); string name = "demo";
channel.QueueDeclare( queue: name, durable: false, exclusive: false, autoDelete: false, arguments: null );
var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { byte[] message = ea.Body.ToArray(); Console.WriteLine("接收到消息为:" + Encoding.UTF8.GetString(message)); };
channel.BasicConsume(name, true, consumer); Console.ReadKey(); channel.Dispose(); conn.Close(); } } }
|