RabbitMqConfig.java 1.54 KB
package com.topdraw.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfig {

    public static final String UCE_EXCHANGE = "uce.exchange";
    public static final String UCE_QUEUE = "uce.queue";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public String getExchange() {

        String exchange = this.rabbitTemplate.getExchange();
        if (StringUtils.isNotBlank(exchange)) {
            return exchange;
        }

        return UCE_EXCHANGE;
    }

    public String getQueue() {
        String queue = this.rabbitTemplate.getRoutingKey();
        if (StringUtils.isNotBlank(queue)) {
            return queue;
        }

        return UCE_QUEUE;
    }

    @Bean
    DirectExchange directExchange(){
        return ExchangeBuilder.directExchange(this.getExchange()).build();
    }

    @Bean
    Queue queue(){ return new Queue(this.getQueue()); }

    @Bean
    Binding binding(DirectExchange directExchange , Queue queue) {
        BindingBuilder.DirectExchangeRoutingKeyConfigurer directExchangeRoutingKeyConfigurer =
                BindingBuilder.bind(queue).to(directExchange);
        return directExchangeRoutingKeyConfigurer.with(this.getQueue());
    }

}