1.导入依赖包
com.rabbitmq
amqp-client
3.4.1
2.获得连接
public class ConnectionUtil {
public static Connection getConnection() throws Exception {
//定义连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置服务地址
factory.setHost("localhost");
//端口
factory.setPort(5672);
//设置账号信息,用户名、密码、vhost
factory.setVirtualHost("testhost");
factory.setUsername("admin");
factory.setPassword("admin");
// 通过工程获取连接
Connection connection = factory.newConnection();
return connection;
}
}
3.生产者发送交易到消费者
public class Send {
private final static String QUEUE_NAME = "q_test_01";
public static void main(String[] argv) throws Exception {
// 获取到连接以及mq通道
Connection connection = ConnectionUtil.getConnection();
// 从连接中创建通道
Channel channel = connection.createChannel();
// 声明(创建)队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 消息内容
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
//关闭通道和连接
channel.close();
connection.close();
}
}
4.消费者从队列中获取消息
public class Recv {
private final static String QUEUE_NAME = "q_test_01";
public static void main(String[] argv) throws Exception {
// 获取到连接以及mq通道
Connection connection = ConnectionUtil.getConnection();
// 从连接中创建通道
Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 定义队列的消费者
QueueingConsumer consumer = new QueueingConsumer(channel);
// 监听队列
channel.basicConsume(QUEUE_NAME, true, consumer);
// 获取消息
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
}
}
}
可以通过配置交换机,配置队列,实现一个消息分发多个队列。配置监听器实现客户端功能。
springframework.amqp 将 rabbitMQ 集成了,可以直接使用这个jar包,
spring-boot-starter-amqp
<rabbit:connection-factory id=“connectionFactory”
host=“127.0.0.1” port=“5672” username=“admin” password=“admin”
virtual-host=“testhost” />
<rabbit:admin connection-factory=“connectionFactory” />
<rabbit:direct-exchange name=“directExchange” auto-declare=“true” ></rabbit:direct-exchange>
<rabbit:template id=“amqpTemplate” connection-factory=“connectionFactory” exchange=“directExchange” />
实现生产者和监听者就可以了。