@RabittListener忽略routingKey

时间:2019-02-07 14:53:09

标签: amqp spring-amqp

在生产者端,我正在发送多个序列为json字符串的对象类型。为了区别起见,我将类名作为路由键发送。

在使用方,我尝试使用多个@RabittListener配置,每个配置具有不同的路由密钥,以便仅处理相应的类。

但是它不起作用,带有其他路由键的邮件将路由到该方法。

我在这里做什么错了?

/**
 * Sends an arbitrary object via the configured queue to a amqp instance. To distinguish the message types on the consumer side, we send the message with
 * the objects class name as a routing key.
 *
 * The object is sent as serialized json object
 *
 * @param obj
 * @throws TurbineException
 */
public void send(Object obj) throws TurbineException {

    if (enabled) {
        String routingKey = obj.getClass().getName();
        String json = serializer.toJson(obj);
        byte[] payload = json.getBytes();
        if (connection == null) {
            throw new TurbineException("Trying to send message to RabbitMQ  but connection is null");
        }
        try (Channel channel = connection.createChannel();) {
            log.info(String.format("Sending data of type %s to queue %s", routingKey, queueName));
            log.info(String.format("Data sent: %s", json));
            channel.exchangeDeclare(EMS_META_EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
            channel.queueDeclare(queueName, true, false, false, null);
            channel.queueBind(queueName, EMS_META_EXCHANGE_NAME, routingKey);
            channel.basicPublish(EMS_META_EXCHANGE_NAME, routingKey, null, payload);
        }
        catch (IOException | TimeoutException e) {
            throw new TurbineException(e);
        }
    }
}

@Autowired
private ProfileMetaService profileMetaService;

@RabbitListener(bindings = @QueueBinding(value = @Queue(value = MetaServiceApplication.EMS_META_QUEUE, durable = "true"), exchange = @Exchange(value = MetaServiceApplication.EMS_META_EXCHANGE_NAME), key = "com.xaxis.janus.turbine.modeling.profile.ProfileMeta"))
@Transactional
public void processMessage(Message message) {
    try {
        String msg = new String(message.getBody());
        if (LOG.isDebugEnabled()) {
            LOG.debug("ProfileMeta received: {}", msg);
        }
        ProfileMeta profileMeta = fromJson(msg, ProfileMeta.class);
        profileMetaService.save(profileMeta);
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}

1 个答案:

答案 0 :(得分:0)

RabbitMQ / AMQP无法正常工作;您需要为每个路由键使用不同的队列。

消费者无法基于用于路由消息的密钥从队列中“选择”消息。

路由在交换中完成;每个消费者都需要自己的队列。