依赖
<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 sendMessageByTopic() throws Exception {
Connection connection = MyRabbitFactory.getConnection();
Channel channel = connection.createChannel();
String msg = UUID.randomUUID().toString().substring(0, 6);
channel.exchangeDeclare("mytopic", "topic", true);
channel.basicPublish("mytopic", "key.11", null, msg.getBytes());
System.out.println("发送完成");
channel.close();
connection.close();
}
接收消息
public void receiveMessageByTopic() throws Exception {
Connection connection = MyRabbitFactory.getConnection();
Channel channel = connection.createChannel();
channel.queueBind("topicqueue", "mytopic", "key.*");
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.basicConsume("topicqueue", true, defaultConsumer);
}