如何在Rabbit回复中将对象转换为Json?

时间:2017-06-08 21:19:07

标签: spring-amqp spring-rabbitmq

我有两个应用程序使用兔子相互通信。

我需要将(从app1)一个对象发送到一个监听器(在app2中)并在一些进程(在监听器上)之后用另一个对象回复我,现在我收到了这个错误: ClassNotFound

我在两个应用程序中都使用此配置为兔子:

@Configuration
public class RabbitConfiguration {

    public final static String EXCHANGE_NAME = "paymentExchange";

    public final static String EVENT_ROUTING_KEY = "eventRoute";
    public final static String PAYEMNT_ROUTING_KEY = "paymentRoute";

    public final static String QUEUE_EVENT = EXCHANGE_NAME + "." + "event";
    public final static String QUEUE_PAYMENT = EXCHANGE_NAME + "." + "payment";
    public final static String QUEUE_CAPTURE = EXCHANGE_NAME + "." + "capture";

    @Bean
    public List<Declarable> ds() {
        return queues(QUEUE_EVENT, QUEUE_PAYMENT);
    }

    @Autowired
    private ConnectionFactory rabbitConnectionFactory;

    @Bean
    public AmqpAdmin amqpAdmin() {
        return new RabbitAdmin(rabbitConnectionFactory);
    }

    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(EXCHANGE_NAME);
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate r = new RabbitTemplate(rabbitConnectionFactory);
        r.setExchange(EXCHANGE_NAME);
        r.setChannelTransacted(false);
        r.setConnectionFactory(rabbitConnectionFactory);
        r.setMessageConverter(jsonMessageConverter());
        return r;
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    private List<Declarable> queues(String... nomes) {
        List<Declarable> result = new ArrayList<>();

        for (int i = 0; i < nomes.length; i++) {
            result.add(newQueue(nomes[i]));
            if (nomes[i].equals(QUEUE_EVENT))
                result.add(makeBindingToQueue(nomes[i], EVENT_ROUTING_KEY));
            else
                result.add(makeBindingToQueue(nomes[i], PAYEMNT_ROUTING_KEY));
        }
        return result;
    }

    private static Binding makeBindingToQueue(String queueName, String route) {
        return new Binding(queueName, DestinationType.QUEUE, EXCHANGE_NAME, route, null);
    }

    private static Queue newQueue(String nome) {
        return new Queue(nome);
    }

}

我使用以下方式发送消息:

String response = (String) rabbitTemplate.convertSendAndReceive(RabbitConfiguration.EXCHANGE_NAME,
            RabbitConfiguration.PAYEMNT_ROUTING_KEY, domainEvent);

等待使用强制转换对象的响应。

此通信使用相同的Rabbit服务器在两个不同的应用程序之间。

我该如何解决这个问题?

我预计兔子会在发送操作中将消息转换为json,并且在回复中也是如此,所以我创建的对象对应于json的回复。

1 个答案:

答案 0 :(得分:4)

请显示侦听器的配置。您应确保ListenerContainer附带了Jackson2JsonMessageConverter以及__TypeId__标题,并附上回复。

另请参阅Spring AMQP JSON sample以获取一些帮助。