1.RabbitMQ的安装
链接:https://blog.csdn.net/Kedongyu_/article/details/97888531
2.简单队列
P:消息的生产者
C:消息的消费者
红色:队列
编写RabbitMQConfig配置类
@Configuration
public class RabbitMQConfig {
@Value("${mq.server.host}")
private String host;
@Value("${mq.server.port}")
private int port;
@Value("${mq.username}")
private String username;
@Value("${mq.password}")
private String password;
@Value("${mq.virtual.host}")
private String virtualHost;
@Bean
public Connection getConnection() throws Exception {
//定义连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置服务地址
factory.setHost(host);
//端口
factory.setPort(port);
//设置账号信息,用户名、密码、vhost
factory.setVirtualHost(virtualHost);
factory.setUsername(username);
factory.setPassword(password);
// 通过工程获取连接
return factory.newConnection();
}
}
配置文件
dubbo.registry.address = 106.14.226.75:2181
#server.port = :diko:{/remote/load/server.port}
server.port = :diko:{/remote/load/server.port}
mq.username = :diko:{/remote/load/mq.username}
mq.password = :diko:{/remote/load/mq.password}
mq.server.host = :diko:{/remote/load/mq.server.host}
mq.server.port = :diko:{/remote/load/mq.server.port}
mq.virtual.host = :diko:{/remote/load/mq.virtual.host}
这里使用自定义配置中心,自行替换,
或者查看 Spring boot 通过zookeeper实现微服务配置中心:https://blog.csdn.net/Kedongyu_/article/details/97883214
生产者编码
@Component
public class Sender {
private final static String QUEUE_NAME = "q_test_01";
@Autowired
private Connection connection;
public void send(String message) throws Exception {
// 从连接中创建通道
Channel channel = connection.createChannel();
// 声明(创建)队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
//关闭通道和连接
channel.close();
}
}
消费者编码
@Component
public class Receiver {
private final static String QUEUE_NAME = "q_test_01";
@Autowired
private Connection connection;
public String receive() throws IOException, InterruptedException {
Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.basicQos(1);
// 定义队列的消费者
QueueingConsumer consumer = new QueueingConsumer(channel);
// 监听队列
channel.basicConsume(QUEUE_NAME, false, consumer);
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
channel.close();
return message;
}
}
测试
@RestController
@RequestMapping("/")
public class SendController {
@Autowired
private Sender sender;
@Autowired
private Receiver receiver;
@RequestMapping("send")
public String send(String message) throws Exception{
sender.send(message);
return "";
}
@RequestMapping("recv")
public String recv() throws Exception{
return receiver.receive();
}
}
运行结果
生产者:
Rabbit后台
消费者: