RabbitMQ动态创建生产者动态创建消费者

生产者 controller

package org.log.rabbitmqdemo1.demos.web.producer;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class ProducerController {

    @Resource
    private ProducerQueueManagementService producerQueueManagementService;

    private final static String QUEUE_NAME_TEMPLATE = "queue_";

    private final static String EXCHANGE_NAME_TEMPLATE = "exchange_";

    private final static String ROUTING_KEY_TEMPLATE = "routing_";

    @GetMapping("/send")
    public void send(String tenantId, String msg, Integer priority) {
        producerQueueManagementService.sendMessage(QUEUE_NAME_TEMPLATE+tenantId,
                EXCHANGE_NAME_TEMPLATE+tenantId,ROUTING_KEY_TEMPLATE+tenantId,
                msg,priority);
    }
}

生产者service

package org.log.rabbitmqdemo1.demos.web.producer;

import org.log.rabbitmqdemo1.demos.web.consumer.QueueManagementService;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class ProducerQueueManagementService {

    private final RabbitAdmin rabbitAdmin;
    private final RabbitTemplate rabbitTemplate;
    private final QueueManagementService queueManagementService;


    @Autowired
    public ProducerQueueManagementService(RabbitTemplate rabbitTemplate, QueueManagementService queueManagementService) {
        this.rabbitAdmin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());
        this.rabbitTemplate = rabbitTemplate;
        this.queueManagementService = queueManagementService;
    }

    public void sendMessage(String queueName, String exchangeName,
                            String routingKey, String message, Integer priority) {

        QueueInformation queueInfo = rabbitAdmin.getQueueInfo(queueName);
        if (null == queueInfo){
            this.createQueueWithPriority(queueName, exchangeName, routingKey);
            queueManagementService.createMessageListener(queueName);
        }

        MessageProperties messageProperties = new MessageProperties();
        // 设置消息的优先级
        messageProperties.setPriority(priority);
        Message msg = new Message(message.getBytes(), messageProperties);
        rabbitTemplate.send(exchangeName, routingKey, msg);
    }

    public void createQueueWithPriority(String queueName, String exchangeName, String routingKey) {
        // 设置队列参数
        Map<String, Object> args = new HashMap<>();
        // 设置最大优先级
        args.put("x-max-priority", 255);

        // 创建队列
        Queue queue = new Queue(queueName, true, false, false, args);

        // 创建交换器
        DirectExchange exchange = new DirectExchange(exchangeName);

        // 声明队列
        rabbitAdmin.declareQueue(queue);

        // 声明交换器
        rabbitAdmin.declareExchange(exchange);

        // 声明绑定关系
        Binding binding = BindingBuilder.bind(queue).to(exchange).with(routingKey);
        rabbitAdmin.declareBinding(binding);
    }

}

消费者service

package org.log.rabbitmqdemo1.demos.web.consumer;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class QueueManagementService {

    private final SimpleMessageListenerContainer container;

    @Autowired
    public QueueManagementService(ConnectionFactory connectionFactory) {
        this.container = new SimpleMessageListenerContainer(connectionFactory);
        this.container.setAutoStartup(false);
    }

    public void createMessageListener(String queueName) {
        DynamicQueueConsumer consumer = new DynamicQueueConsumer();
        SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(container.getConnectionFactory());
        listenerContainer.setQueueNames(queueName);

        // 使用 MessageListenerAdapter 来包装 DynamicQueueConsumer
        MessageListenerAdapter adapter = new MessageListenerAdapter(consumer, "onMessage");
        adapter.setDelegate(consumer);
        listenerContainer.setMessageListener(adapter);

        listenerContainer.start();
    }
}

消费者

package org.log.rabbitmqdemo1.demos.web.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class DynamicQueueConsumer implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        System.out.println(this);
        TimeUnit.SECONDS.sleep(5);
        // 处理消息
        System.out.println("顺序:" + message.getMessageProperties().getPriority());
        System.out.println("Received message: " + new String(message.getBody()));
        TimeUnit.SECONDS.sleep(5);
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值