【Spring】使用Spring和AMQP发送接收消息(中)

上篇讲了RabbitMQ连接工厂的作用是用来创建RabbitMQ的连接,本篇就来讲讲RabbitMQ的发送消息。通过RabbitMQ发送消息最简单的方式就是将connectionFactory Bean注入到服务层类中,并使用它创建Connection,使用这个Connection来创建Channel,再使用这个Channel发布消息到Exchange中。

当然Spring AMQP提供了RabbitTemplate来简便我们的操作,消除RabbitMQ发送和接收消息相关的样板代码。使用RabbitTemplate也是先在配置文件中写相关的配置,使用Rabbit命名空间的<template>元素,如下:

<template id="rabbitTemplate" connection-factory="connectionFactory">

现在要发送消息只需要将模板bean注入到服务层类中(这里以SendServiceImpl为例),并使用它来发送Spittle,使用RabbitTemplate来发送Spittle提醒,代码如下:
public class SendServiceImpl implements SendService {
    private RabbitTemplate rabbit;

    @Autowired
    public SendServiceImpl (RabbitTemplate rabbit) {
        this.rabbit = rabbit;
    }

    public void sendSpittle (Spittle spittle) {
        rabbit.convertAndSend("spittle.test.exchange", "spittle.test", spittle);
    }
}

上面代码中sendSpittle()调用RabbitTemplate的convertAndSend()方法,传入的三个参数分别是Exchange的名称、routing key以及要发送的对象。
这里如果使用最简单的只传要发送的对象的重载方法,RabbitTemplate就使用默认的Exchange和routing key。按之前配置的话,这两项默认都为空,也可以自行在<template>元素上借助exchange和routing-key属性配置不同的默认值:

<template id="rabbitTemplate" connection-factory="connectionFactory"
    exchange="spittle.test.exchange" 
    routing-key="spittle.test" />

此外RabbitTemplate还有其他方法可以用来发送消息,比如用send()方法来发送org.springframework.amqp.core.Message对象,如下所示:

Message message = new Message("Hello World".getBytes(), new MessageProperties());
rabbit.send("hello.exchange", "hello.routing", message);


使用send()方法的技巧在于构造要发送的Message对象,在上面的例子中,通过给定字符串的字节数组来构建Message实例。这里是字符串相对比较简单,如果消息是复杂对象的话,则会比较复杂。也是因为这样,所以一般会用convertAndSend()方法,它会自动将对象转换为Message,不过它需要一个消息转换器来帮助完成该任务,默认的转换器是SimpleMessageConverter,它适用于String、Serializable实例和字节数组。

猜你喜欢

转载自weknow619.iteye.com/blog/2364603