RabbitMQ工作模式代码

RabbitMQ工作模式代码

队列

生产者生产的消息,由消费者消费,每条消息只会被一个消费者给消费

  • 生产者
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("ip");
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("username");
        connectionFactory.setPassword("pwd");
        // 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        // 通过connection创建一个channel
        Channel channel = connection.createChannel();
        // 添加属性
        Map<String,Object> map = new HashMap<>();
        map.put("arg1","arg1");
        map.put("arg2","arg2");
        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .deliveryMode(2) // 2 持久化,1不持久化
                .contentEncoding("UTF-8")
                .expiration("15000") // 15秒过期
                .headers(map)
                .build();
        // 发送数据
        for (int i = 0; i < 5; i++) {
            String message = "hello rabbitmq" + i;
            channel.basicPublish("","test001",properties,message.getBytes());
        }
        // 关闭连接
        channel.close();
        connection.close();
    }
}
  • 消费者
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("ip");
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("username");
        connectionFactory.setPassword("pwd");
        // 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        // 通过connection创建一个channel
        Channel channel = connection.createChannel();
        // 声明一个队列
        channel.queueDeclare("test001",true,false,false,null);
        // 设置channel
        channel.basicConsume("test001",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费端:" + new String(body));
            }
        });
    }
}

发布订阅模式

消费者定义一个队列,绑定到同一个交换机,则每个消费者都能消费到消息

  • 生产者
public class Producer {
    public static void main(String[] args) throws Exception {
        // 创建连接工厂并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("ip");
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("username");
        connectionFactory.setPassword("password");
        // 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        // 通过connection创建一个channel
        Channel channel = connection.createChannel();
        channel.exchangeDeclare("test-pubsub", BuiltinExchangeType.FANOUT);
        String message = "test-pub/sub模式";
        channel.basicPublish("test-pubsub", "", null, message.getBytes("UTF-8"));
        channel.close();
        connection.close();
    }
}
  • 消费者
public class Consumer {
    public static void main(String[] args) throws Exception {
        // 创建连接工厂并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("ip");
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("username");
        connectionFactory.setPassword("password");
        // 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        // 通过connection创建一个channel
        Channel channel = connection.createChannel();
        // 声明一个交换机
        channel.exchangeDeclare("test-pubsub", BuiltinExchangeType.FANOUT);
        String queue = "test-pubsub001";
        channel.queueDeclare(queue,false,false,false,null);
        // 绑定队列
        channel.queueBind(queue,"test-pubsub","");
        // 设置channel
        channel.basicConsume(queue,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费端:" + new String(body));
            }
        });
    }
}

路由模式

消费者根据绑定的不同路由键来消费生产者发布的消息。

  • 生产者
public class Producer {
    public static void main(String[] args) throws Exception {
        // 创建连接工厂并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("ip");
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("username");
        connectionFactory.setPassword("password");
        // 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        // 通过connection创建一个channel
        Channel channel = connection.createChannel();
        String exchange = "test-route";
        channel.exchangeDeclare(exchange, BuiltinExchangeType.DIRECT);
        String message = "test-route模式";
        channel.basicPublish(exchange, "route-key-01", null, message.getBytes("UTF-8"));
        channel.basicPublish(exchange, "route-key-02", null, message.getBytes("UTF-8"));
        channel.close();
        connection.close();
    }
}
  • 消费者
public class Consumer {
    public static void main(String[] args) throws Exception {
        // 创建连接工厂并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("ip");
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("username");
        connectionFactory.setPassword("password");
        // 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        // 通过connection创建一个channel
        Channel channel = connection.createChannel();
        // 声明一个交换机
        String exchange = "test-route";
        channel.exchangeDeclare(exchange, BuiltinExchangeType.DIRECT);
        String queue = channel.queueDeclare().getQueue();
        // 绑定队列
        channel.queueBind(queue,exchange,"route-key-01");

        // 设置channel
        channel.basicConsume(queue,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费端1:" + new String(body));
            }
        });
    }
}
// ----- 消费者2
public class Consumer2 {
    public static void main(String[] args) throws Exception {
        // 创建连接工厂并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("ip");
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("username");
        connectionFactory.setPassword("password");
        // 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        // 通过connection创建一个channel
        Channel channel = connection.createChannel();
        // 声明一个交换机
        String exchange = "test-route";
        channel.exchangeDeclare(exchange, BuiltinExchangeType.DIRECT);
        String queue = channel.queueDeclare().getQueue();
        // 绑定队列
        channel.queueBind(queue,exchange,"route-key-02");

        // 设置channel
        channel.basicConsume(queue,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费端2:" + new String(body));
            }
        });
    }
}

主题模式

主题模式时,队列绑定到交换机,bingdingkey时使用通配符,消息转发到队列时会根据routingkey进行模糊匹配

  • 生产者
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("ip");
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("username");
        connectionFactory.setPassword("password");
        // 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        // 通过connection创建一个channel
        Channel channel = connection.createChannel();

        channel.exchangeDeclare("test-topic", BuiltinExchangeType.TOPIC);
        String message = "test-topic模式";
        channel.basicPublish("test-topic", "a.b.c", null, message.getBytes("UTF-8"));
        channel.close();
        connection.close();
    }
}
  • 消费者
public class Consumer {
    public static void main(String[] args) throws Exception {
        // 创建连接工厂并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("ip");
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("username");
        connectionFactory.setPassword("password");
        // 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        // 通过connection创建一个channel
        Channel channel = connection.createChannel();
        // 声明一个交换机
        channel.exchangeDeclare("test-topic", BuiltinExchangeType.TOPIC);
        String queue = channel.queueDeclare().getQueue();
        System.err.println("queue:" + queue);
        // 绑定队列
        channel.queueBind(queue,"test-topic","a.b.*");

        // 设置channel
        channel.basicConsume(queue,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费端1:" + new String(body));
            }
        });
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值