RabbitMQ官网下载地址:Downloading and Installing RabbitMQ — RabbitMQ
yum install build-essential openssl openssl-devel unixODBC unixODBC-devel make gcc gcc-c++ kernel-devel m4 ncurses-devel tk tc xz
上传安装包到linux 环境
rpm -ivh erlang-23.3.4.5-1.el7.x86_64.rpm
sudo yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make -y
安装socat
yum install socat -y
安装rabbitMQ
rpm -ivh rabbitmq-server-3.8.34-1.suse.noarch.rpm
开启管理界面
rabbitmq-plugins enable rabbitmq_management
启动rabbitmq
/bin/systemctl start rabbitmq-server.service
开放端口
firewall-cmd --zone=public --add-port=15672/tcp --permanent firewall-cmd --zone=public --add-port=5672/tcp --permanent firewall-cmd --reload
查看服务状态
/sbin/service rabbitmq-server status
停止服务
/sbin/service rabbitmq-server stop
添加开机自启动
chkconfig rabbitmq-server on
添加账户密码
rabbitmqctl add_user sy 123456
设置角色
rabbitmqctl set_user_tags sy administrator
设置用户权限
rabbitmqctl set_permissions -p "/" sy ".*" ".*" ".*"
查看用户和角色
rabbitmqctl list_users
关闭rabbitMQ
rabbitmqctl stop_app
重置命令
rabbitmqctl reset
重新启动
rabbitmqctl start_app
查看主机名称
hostnamectl status
hostnamectl set-hostname localhost.localdomain
生产者
public class ProducerDemo1 {
//队列名称
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws IOException {
//建立连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置目标主机ip
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
// 修改端口
// factory.setPort();
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
/*
queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
Map arguments)
参数说明:
queue: 队列名称
durable: 是否持久化
exclusive: 是否一个消费者监听一个队列
autoDelete:是否自动删除。如果没有消费者,自动删除队列
arguments:参数
*/
//通道和队列的连接
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//需要发送的消息
String message = "Hello RabbitMQ";
//通过最基础的发布
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}catch (Exception e) {
e.printStackTrace();
}
}
}
消费者
public class Consumer {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
//建立连接
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
public class ProducerQueue {
//队列名称
private final static String QUEUE_NAME = "work_queue";
public static void main(String[] args) throws IOException {
//建立连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置目标主机ip
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
// 修改端口
// factory.setPort();
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
//通道和队列的连接
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
for (int i = 0; i < 10; i++) {
//需要发送的消息
String message = "Hello RabbitMQ"+i;
//通过最基础的发布
channel.basicPublish("", QUEUE_NAME,
MessageProperties.PERSISTENT_TEXT_PLAIN,
message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
public class ConsumerQueue {
private final static String QUEUE_NAME = "work_queue";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
//建立连接
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.basicQos(1);//如果你的消息还没确认,那么同一时间只给你发送一条消息
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
public class ConsumerQueue2 {
private final static String QUEUE_NAME = "work_queue";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
//建立连接
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.basicQos(1);//如果你的消息还没确认,那么同一时间只给你发送一条消息
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
生产者代码
public class ProducerPubSub {
//交换机名称
private final static String EXCHANGE_NAME = "logs";
public static void main(String[] args) throws IOException {
//建立连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置目标主机ip
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
// 修改端口
// factory.setPort();
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
//信道和交换机的绑定
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
//创建队列
String queue1 = "fanout_queue_1";
String queue2 = "fanout_queue_2";
channel.queueDeclare(queue1,true,false,false,null);
channel.queueDeclare(queue2,true,false,false,null);
//通道和队列连接
channel.queueBind(queue1, EXCHANGE_NAME, "");
channel.queueBind(queue2, EXCHANGE_NAME, "");
/*routingKey 如果在fanout模式下,指定""*/
for (int i = 0; i < 10; i++) {
//需要发送的消息
String message = "Hello RabbitMQ"+i;
//通过最基础的发布
channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
消费者代码
public class ConsumerPubSub {
//指定接收队列名称String queue1 = "fanout_queue_1"
private final static String QUEUE_NAME = "fanout_queue_1";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
//建立连接
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(QUEUE_NAME, "fanout");
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
channel.basicQos(1);//如果你的消息还没确认,那么同一时间只给你发送一条消息
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
public class ProducerRouting {
//交换机名称
private final static String EXCHANGE_NAME = "direct_logs";
public static void main(String[] args) throws IOException {
//建立连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置目标主机ip
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
// 修改端口
// factory.setPort();
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
//信道和交换机的绑定
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
//创建队列
String queue1 = "direct_queue_1";
String queue2 = "direct_queue_2";
channel.queueDeclare(queue1,true,false,false,null);
channel.queueDeclare(queue2,true,false,false,null);
//通道和队列连接
channel.queueBind(queue1, EXCHANGE_NAME, "error");
channel.queueBind(queue2, EXCHANGE_NAME, "error");
channel.queueBind(queue2, EXCHANGE_NAME, "info");
channel.queueBind(queue2, EXCHANGE_NAME, "warning");
/*routingKey 如果在fanout模式下,指定""*/
for (int i = 0; i < 10; i++) {
//需要发送的消息
String message = "Hello RabbitMQ"+i;
//通过最基础的发布
if (i % 2 ==0){
channel.basicPublish(EXCHANGE_NAME, "error", null, message.getBytes());
}else{
channel.basicPublish(EXCHANGE_NAME, "info", null, message.getBytes());
}
System.out.println(" [x] Sent '" + message + "'");
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
public class ConsumerRouting {
private final static String QUEUE_NAME = "direct_queue_1";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
//建立连接
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(QUEUE_NAME, "fanout");
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
channel.basicQos(1);//如果你的消息还没确认,那么同一时间只给你发送一条消息
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
另外两个消费者改成队列2,其他代码不变
public class ProducerTopic {
//交换机名称
private final static String EXCHANGE_NAME = "topic_logs";
public static void main(String[] args) throws IOException {
//建立连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置目标主机ip
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
// 修改端口
// factory.setPort();
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
//信道和交换机的绑定
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
//创建队列
String queue1 = "topic_queue_1";//只记录订单数据wj.order.#
String queue2 = "topic_queue_2";//wj.# *.log.#
channel.queueDeclare(queue1,true,false,false,null);
channel.queueDeclare(queue2,true,false,false,null);
//通道和队列连接
channel.queueBind(queue1, EXCHANGE_NAME, "wj.order.#");
channel.queueBind(queue2, EXCHANGE_NAME, "wj.#");
channel.queueBind(queue2, EXCHANGE_NAME, "*.log.#");
/*routingKey 如果在fanout模式下,指定""*/
for (int i = 0; i < 10; i++) {
//需要发送的消息
String message = "Hello RabbitMQ"+i;
//通过最基础的发布
if (i % 2 ==0){
channel.basicPublish(EXCHANGE_NAME, "wj.order.save", null, message.getBytes());
}else{
channel.basicPublish(EXCHANGE_NAME, "tx.log.save", null, message.getBytes());
}
System.out.println(" [x] Sent '" + message + "'");
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
public class ConsumerTopic {
private final static String QUEUE_NAME = "topic_queue_2";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.245.129");
//设置账号名和密码
factory.setUsername("wj");
factory.setPassword("123456");
//建立连接
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(QUEUE_NAME, "fanout");
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
channel.basicQos(1);//如果你的消息还没确认,那么同一时间只给你发送一条消息
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
RabbitMqConfig
@Configuration
@EnableRabbit
public class RabbitMqConfig {
/**
* 创建队列成功//core.Queue
*/
@Bean
public Queue helloQueue(){
return new Queue("springboot-queue",true);
}
//创建topic队列
@Bean
public Queue topicQueue(){
return new Queue("springboot-topic-queue",true);
}
//创建交换机
@Bean
public TopicExchange topicExchange(){
return new TopicExchange("topicExchange");
}
//绑定交换机与消息队列
@Bean
public Binding topicBing(){
return BindingBuilder
.bind(topicQueue())//绑定队列
.to(topicExchange())//绑定交换机
.with("wj.*");//制定路由器key
}
}
spring:
rabbitmq:
host: 192.168.245.129
port: 5672
username: wj
password: 123456
@SpringBootTest
class SpringbootRabbitmqSendApplicationTests {
@Autowired
RabbitTemplate template;
@Autowired
Queue helloQueue;
@Test
void contextLoads() {
template.convertAndSend(helloQueue.getName(),"hello springboot");
}
@SpringBootTest
class SpringbootRabbitmqSendApplicationTests {
@Autowired
RabbitTemplate template;
@Autowired
Queue helloQueue;
@Test
void contextLoads() {
template.convertAndSend(helloQueue.getName(),"hello springboot");
}
@Test
void send2Topic(){
template.convertAndSend("topicExchange","wj.order","123456");
}
}
配置文件同生产者
@Service
public class MessageReceive {
@RabbitListener(queues = {"springboot-queue","springboot-topic-queue"})
public void receive(String body){
System.out.println(body);
}
}
@Configuration
@EnableRabbit
public class RabbitMqConfig {
//创建库存队列
@Bean
public Queue inventoryQueue(){
return new Queue("inventory-queue",true);
}
//创建支付队列
@Bean
public Queue payQueue(){
return new Queue("pay-queue",true);
}
//创建交换机
@Bean
public TopicExchange orderExchange(){
return new TopicExchange("orderExchange");
}
//绑定交换机与消息队列
@Bean
public Binding inventoryBing(){
Binding order = BindingBuilder
.bind(inventoryQueue())//绑定队列
.to(orderExchange())//绑定交换机
.with("order.#");//制定路由器key
return order;
}
@Bean
public Binding payBing(){
Binding order = BindingBuilder
.bind(payQueue())//绑定队列
.to(orderExchange())//绑定交换机
.with("order.#");//制定路由器key
return order;
}
}
@Service
public class MessageReceive {
@RabbitListener(queues = {"order-queue"})
public void receive(String body){
System.out.println(body);
}
}
@Service
public class MessageReceive {
@RabbitListener(queues = {"order-queue"})
public void receive(String body){
System.out.println(body);
}
}