java rabbitmq 工具类_第二章: Java整合RabbitMQ

导入依赖

com.rabbitmq

amqp-client

5.6.0

编写工具类

public class RabbitMQUtil {

private static Connection connection;

public static synchronized Connection getConnection() throws Exception {

if (connection == null) {

ConnectionFactory factory = new ConnectionFactory();

factory.setHost("127.0.0.1");

factory.setPort(5672);

factory.setVirtualHost("/");

factory.setUsername("guest");

factory.setPassword("guest");

connection = factory.newConnection();

}

return connection;

}

}

编写生产者

public class RabbitMQProducer {

public static void main(String[] args) throws Exception {

// 1. 获取连接

Connection connection = RabbitMQUtil.getConnection();

// 2. 获取通道

Channel channel = connection.createChannel();

// 3. 创建交换机

channel.exchangeDeclare("test_exchange", BuiltinExchangeType.TOPIC, true);

// 4. 创建队列

channel.queueDeclare("test_queue_1",true,false,false,null);

channel.queueDeclare("test_queue_2",true,false,false,null);

channel.queueDeclare("test_queue_3",true,false,false,null);

// 5. 绑定队列和交换机

channel.queueBind("test_queue_1","test_exchange", "#.world");

channel.queueBind("test_queue_2","test_exchange", "hello.#");

channel.queueBind("test_queue_3","test_exchange", "hello.world");

// 6. 发送消息

for (int i = 0; i < 5; i++) {

channel.basicPublish("test_exchange", "hello.world",null, "hello, world".getBytes());

}

// 7. 关闭资源

channel.close();

connection.close();

}

}

编写消费者

public class RabbitMQConsumer {

public static void main(String[] args) throws Exception {

Connection connection = RabbitMQUtil.getConnection();

Thread consumer1 = new Thread(new ConsumerThread(connection, "test_queue_1"));

consumer1.start();

Thread consumer2 = new Thread(new ConsumerThread(connection, "test_queue_2"));

consumer2.start();

Thread consumer3 = new Thread(new ConsumerThread(connection, "test_queue_3"));

consumer3.start();

}

static class ConsumerThread implements Runnable {

private Connection connection;

private String queue;

public ConsumerThread(Connection connection, String queue) {

this.connection = connection;

this.queue = queue;

}

public void run() {

try {

Channel channel = connection.createChannel();

Consumer consumer = new DefaultConsumer(channel) {

@Override

public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

System.out.println(queue + ": " + new String(body));

}

};

channel.basicConsume(queue, true, consumer);

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值