pom.xml
4.0.0 org.example RabbitMQ 1.0-SNAPSHOT 8 8 com.rabbitmq amqp-client 5.6.0 org.slf4j slf4j-log4j12 1.7.21 test log4j log4j 1.2.17
Rabbit工具类:RabbitMQUtils
在提供者和消费者中有一段相同代码,可以抽取封装成工具类
package com.example.newRabbit;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class RabbitMQUtils {
public static Connection getConnection() throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory(); //获取创建连接的工厂
connectionFactory.setHost("localhost"); //设置服务主机地址
connectionFactory.setPort(5672); //设置端口,默认5672
connectionFactory.setVirtualHost("/"); //设置虚拟主机地址
connectionFactory.setUsername("chocoMoss"); //设置用户名
connectionFactory.setPassword("123456"); //设置密码
Connection connection = connectionFactory.newConnection(); //创建连接
return connection;
}
}
提供者:Rabbit_provider
queueDeclare 里的参数1 和 basicPublish 的参数2要相同
package com.example.newRabbit;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Rabbit_provider {
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = RabbitMQUtils.getConnection();
//创建通道
Channel channel = connection.createChannel();
channel.queueDeclare("chocoMoss",true,false,false,null);
//创建消息
String message= "hello world";
channel.basicPublish("","chocoMoss",null,message.getBytes());
//关闭资源
channel.close();
connection.close();
}
}
消费者:Rabbit_consumer
package com.example.newRabbit;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Rabbit_consumer {
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = RabbitMQUtils.getConnection();
//创建通道
Channel channel = connection.createChannel();
//创建队列
channel.queueDeclare("chocoMoss",true,false,false,null);
//创建消费者,并设置消息处理
DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//路由的key
String routingKey = envelope.getRoutingKey();
//获取交换机信息
String exchange = envelope.getExchange();
//获取消息ID
long deliveryTag = envelope.getDeliveryTag();
//获取消息信息
String message = new String(body,"UTF-8");
System.out.println("routingKey:"+routingKey+",exchange:"+exchange+",deliveryTag:"+deliveryTag+",message:"+message);
}
};
channel.basicConsume("chocoMoss",true,defaultConsumer);
//关闭资源(不建议关闭,建议一直监听)
// channel.close();
// connection.close();
}
}



