用fanout的方式和java语言写一个发送和接收的示例
时间: 2024-05-14 15:13:12 浏览: 75
路由模式-概率论与数理统计 浙江大学版 第4版(盛骤 谢式千 潘承毅 编著)
Sure, here is an example code for sending and receiving messages using fanout in Java:
```
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class FanoutExample {
private static final String EXCHANGE_NAME = "fanout_example";
public static void main(String[] argv) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, EXCHANGE_NAME, "");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println("Received message: " + message);
}
};
channel.basicConsume(queueName, true, consumer);
String message = "Hello, World!";
channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));
System.out.println("Sent message: " + message);
channel.close();
connection.close();
}
}
```
Hope this helps! Let me know if you have any more questions.
阅读全文