依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.13.0</version>
</dependency>
public class MyRabbitFactory {
public static Connection getConnection() throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
connectionFactory.setVirtualHost("myvh");
Connection connection = connectionFactory.newConnection();
return connection;
}
}
发送消息
public void sendMessag() throws Exception {
Connection connection = MyRabbitFactory.getConnection();
Channel channel = connection.createChannel();
for (int i = 0; i < 10; i++) {
String msg = UUID.randomUUID().toString().substring(0, 6);
channel.basicPublish("", "myqueue", null, msg.getBytes());
}
System.out.println("发送完成");
channel.close();
connection.close();
}
public void sendMessag2() throws Exception {
Connection connection = MyRabbitFactory.getConnection();
Channel channel = connection.createChannel();
String msg = UUID.randomUUID().toString().substring(0, 6);
channel.confirmSelect();
channel.basicPublish("", "myqueue", null, msg.getBytes());
System.out.println("发送完成");
boolean res = channel.waitForConfirms();
if (res) {
System.out.println("发送成功");
} else {
System.out.println("发送失败");
}
channel.close();
connection.close();
}
接收消息
public void receiveMessage() throws Exception {
Connection connection = MyRabbitFactory.getConnection();
Channel channel = connection.createChannel();
channel.basicQos(3);
DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope
, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body, "UTF-8");
System.out.println(msg);
channel.basicAck(envelope.getDeliveryTag(),false);
}
};
channel.basicConsume("myqueue", false, defaultConsumer);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!