如何在 Spring 中获取 Channel 对象启动 AMQP 并创建 "x-consistent-hash" 类型的交换

How to get Channel object in Spring boot AMQP and create a Exchange of type "x-consistent-hash"

RabbitMQ Consistent Hasing Github中提到的创建一致性哈希交换的示例使用 Channel 创建交换:

private static String CONSISTENT_HASH_EXCHANGE_TYPE = "x-consistent-hash";
...
Channel ch = conn.createChannel();
...
ch.exchangeDeclare("e1", CONSISTENT_HASH_EXCHANGE_TYPE, true, false, null);



我尝试使用参数创建一致的哈希交换,但它不起作用:
@Configuration
@EnableAutoConfiguration
public class AMQPConfig {

    public static final String QUEUENAME = "consistentHashing-Q1";
    public static final String EXCHANGENAME = "consistentHashing-DE1";
    public static final String RK = "consistentHashing-RK1";


    @Bean
    public Queue queue() {
        return QueueBuilder.nonDurable(QUEUENAME).autoDelete().build();
    }

    @Bean
    public DirectExchange directExchange()  {
        return ExchangeBuilder.directExchange(EXCHANGENAME).autoDelete().withArgument("Type", "x-consistent-hash").build();
    }

    @Bean
    public Binding binding(Queue queue, Exchange exchange)    {
        return BindingBuilder.bind(queue).to(exchange).with(RK).noargs();
    }
}


  1. 想知道如何在 Spring boot
  2. 中获取 Channel 对象
  3. AMQP?如何在 Spring 引导 AMQP 中创建一致的哈希交换?

Spring AMQP 没有将自定义交换声明为 @Bean 定义的机制,但您可以使用 RabbitTemplate 获取自己声明的通道。

Exchange.DeclareOk = rabbitTemplate.execute(channel -> channel.exchangeDeclare(...));

能够使用以下代码在 Spring 引导 AMQP 中创建一致性哈希交换:

@Bean
public CustomExchange customExchange()  {
    CustomExchange customExchange = new CustomExchange(EXCHANGENAME, "x-consistent-hash", false, true);
    customExchange.addArgument("hash-header", "client-id");
    return customExchange;
}