一、RabbitMQ入门
使用流程
-
创建connectionFactory
-
根据connectionFactory创建connection
// 以下是ConnectionUtil package com.ola.util; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; public class ConnectionUtil { public static Connection getConnection() throws IOException { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost"); connectionFactory.setPort(5672); connectionFactory.setVirtualHost("/"); connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); Connection connection = connectionFactory.newConnection(); return connection; } }
-
通过connection创建channel
-
通过channel创建交换机、声明队列、绑定关系、路由Key、发送消息、接收消息
-
准备消息内容
-
发送消息给队列
-
关闭连接
-
关闭通道
package com.ola.service; import com.ola.util.ConnectionUtil; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import java.io.IOException; public class RabbitMQTest { private static final String EXCHANGE_NAME = "test_exchange_direct"; public static void main(String[] args) throws IOException { Connection connection = ConnectionUtil.getConnection(); Channel channel = connection.createChannel(); String queueName = "queue1"; /** * @params1 队列的名字 * @params2 是否要持久化 * @params3 排他性,是否是独占队列 * @params4 是否自动删除,最后一个消费者消费完毕后是否删除 * @params5 携带附加参数 */ channel.queueDeclare(queueName, false, false, false, null); // channel.exchangeDeclare(EXCHANGE_NAME, "direct"); String msg = "hello"; // channel.basicPublish(EXCHANGE_NAME, "delete", null, msg.getBytes()); channel.basicPublish("", queueName, null, msg.getBytes()); System.out.println("[x] sent '" + msg + "'"); channel.close(); connection.close(); } }
二、RabbitMQ使用
RabbitMQ—C#发送端(Routing模式)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RabbitMQ.Client;
namespace RabbitMQTest002
{
class Program
{
static string EXCHANGE_NAME = "test_exchange_direct";
static string QUEUE_NAME = "queueDirectCSharp001";
static string ROUTE_KEY = "CSharpToJava";
static string TYPE = "direct";
static void Main(string[] args)
{
string message = "Say Hello!1123131!";
var factory = new ConnectionFactory();
factory.HostName = "localhost";
factory.UserName = "guest";
factory.Password = "guest";
factory.Port = 5672;
factory.VirtualHost = "/";
// using用于自动释放对象,避免内存溢出和泄露。
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare(EXCHANGE_NAME,TYPE);
channel.QueueDeclare(QUEUE_NAME,true,false,false,null);
channel.BasicPublish(EXCHANGE_NAME,ROUTE_KEY,null,Encoding.UTF8.GetBytes(message));
Console.WriteLine("发送成功!");
channel.Close();
connection.Close();
}
}
}
}
}
问题:
c#如何引入RabbitMQ类库?
答:在nuget中搜索RabbitMQ.client,然后使用Visual Studio自带的包管理器(Tools-Nuget Package Management插件,输入命令即可)