springboot+RabbitMQ 问题 RabbitListener 动态队列名称:Attribute value must be constant

因为每台机器需要使用自己的队列接受消息
所以尝试使用以下的方案

解决方案----Spring SPEL表达式

@Configuration
@Component
public class DirectRabbitReceiver {

    @Autowired
    private ShardOrderService shardOrderService;  
  
    private static String INFO_QUEUE_NAME;

    private static String CHARGE_QUEUE_NAME;

    private static String CANCEL_QUEUE_NAME;

    @Value("${rabbitmqConfig.infoValue:}")
    public void setInfoValue(String infoValue){
        INFO_QUEUE_NAME = infoValue;
    }
    @Value("${rabbitmqConfig.chargeValue:}")
    public void setChargeValue(String chargeValue){
        CHARGE_QUEUE_NAME = chargeValue;
    }
    @Value("${rabbitmqConfig.cancelValue:}")
    public void setCancelValue(String cancelValue){
        CANCEL_QUEUE_NAME = cancelValue;
    }

    @Bean
    public Queue queue1(){
        System.out.println(DirectRabbitReceiver.INFO_QUEUE_NAME);
        return new Queue(DirectRabbitReceiver.INFO_QUEUE_NAME);
    }
    @Bean
    public Queue queue2(){
        System.out.println(DirectRabbitReceiver.CHARGE_QUEUE_NAME);
        return new Queue(DirectRabbitReceiver.CHARGE_QUEUE_NAME);
    }
    @Bean
    public Queue queue3(){
        return new Queue(DirectRabbitReceiver.CANCEL_QUEUE_NAME);
    }    

 

@RabbitListener(bindings = @QueueBinding(
            value = @org.springframework.amqp.rabbit.annotation.Queue(value = "#{queue1.name}", durable = "true", exclusive = "false", autoDelete = "false"),
            exchange = @Exchange(value="U19013.shareOrder", type= ExchangeTypes.DIRECT),
            key = "#{queue1.name}",ignoreDeclarationExceptions="true"))
    @RabbitHandler
    public void info(String info) throws Exception {
        System.out.println("xd shareOrder info: " + info);
        shardOrderService.bookingOrder(info);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @org.springframework.amqp.rabbit.annotation.Queue(value = "#{queue2.name}", durable = "true", exclusive = "false", autoDelete = "false"),
            exchange = @Exchange(value="U19013.shareOrder", type= ExchangeTypes.DIRECT),
            key = "#{queue2.name}",ignoreDeclarationExceptions="true"))
    @RabbitHandler
    public void charge(String info) throws Exception {
        System.out.println("xd shareOrder charge: " + info);
        shardOrderService.chargeOrder(info);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @org.springframework.amqp.rabbit.annotation.Queue(value = "#{queue3.name}", durable = "true", exclusive = "false", autoDelete = "false"),
            exchange = @Exchange(value="U19013.shareOrder", type= ExchangeTypes.DIRECT),
            key = "#{queue3.name}",ignoreDeclarationExceptions="true"))
    @RabbitHandler
    public void cancel(String info) throws Exception {
        System.out.println("xd shareOrder cancel: " + info);
        shardOrderService.cancelOrder(info);
    }

你可能感兴趣的:(Java,RabbitMQ)