回顾前面,我们进行了RabbitMQ的环境搭建,配置,还有本地代码的简单交互。现在我们来进行远程数据交互,就是说,我们的RabbitMQ.Server和RabbitMQ.Client可以不在同一个服务器,也能进行数据传输。
一、远程账号配置(参考 admin配置)
配置的账号密码,就是用于我们远程服务访问。
二、RabbitMQ.Server 写入代码
static void Main(string[] args){ for (int i = 0; i < 50; i++) { Task.Run(async () => { await CreateProdcut(); }); } Console.ReadLine(); }private static ConnectionFactory factory = new ConnectionFactory() { HostName = "116.28.8.166", UserName = "admin", Password = "********", VirtualHost = "/" };private static Task CreateProdcut(){ return Task.Factory.StartNew(() => { using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { string guid = Guid.NewGuid().ToString(); var body = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); channel.QueueDeclare("AllenLeeQueue", false, false, false, null); channel.BasicPublish("", "AllenLeeQueue", null, body); Console.WriteLine("[Set Msg To AllenLeeQueue] " + guid); } } });}
三、RabbitMQ.Client 写入代码
private static ConnectionFactory factory = new ConnectionFactory() { HostName = "116.28.8.166", UserName = "admin", Password = "********", VirtualHost = "/" };static void Main(string[] args){ factory.AutomaticRecoveryEnabled = true;//设置端口后自动恢复连接属性即可 using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [Get Msg from AllenLeeQueue] {0}", message); }; channel.BasicConsume(queue: "AllenLeeQueue", noAck: true, consumer: consumer); Console.ReadLine(); } }}
四、运行RabbitMQ.Server和RabbitMQ.Client
我们可以看到,我们远程进行了调用,RabbitMQ.Server发送出来的数据,可以在RabbitMQ.Client进行接收,至此我们的远程访问已经成功。这样后续我们就可以在任意的地方,通过RabbitMQ对服务器的数据进行访问获取,
这为我拉后续的并发打下基础。后续我们就会深入到大数据并发的场景,一步步慢慢由浅入深。