RabbitMQ 使用direct交换机发送和接收消息

依赖

<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");
        // 设置VirtualHost
        connectionFactory.setVirtualHost("myvh");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        return connection;
    }
}

发送消息

public void sendMessageByDirect() throws Exception {
    Connection connection = MyRabbitFactory.getConnection();
    // 设置通道
    Channel channel = connection.createChannel();
    // 设置消息
    String msg = UUID.randomUUID().toString().substring(0, 6);
    //mydirect -- 交换机Name;direct -- 交换机类型
    channel.exchangeDeclare("mydirect", "direct", true);
    //发送消息。key 与消费端的 key 对应
    channel.basicPublish("mydirect", "key", null, msg.getBytes());
    System.out.println("发送完成");
    channel.close();
    connection.close();
}

接收消息

public void receiveMessageByDirect() throws Exception {
    Connection connection = MyRabbitFactory.getConnection();
    // 设置通道
    Channel channel = connection.createChannel();
    //发送消息。directqueue -- 队列Name;mydirect -- 交换机Name;key -- 与提供的key对应
    channel.queueBind("directqueue", "mydirect", "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);
        }
    };
    //监听队列;directqueue -- 队列Name;true - 自动确认
    channel.basicConsume("directqueue", true, defaultConsumer);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值