RabbitMQ知识点整理10-发送消息

如果要发送一个消息,可以使用Channel 类的basicPublish 方法,比如发送一条内容为"Hello World! "的消息,参考如下:

byte[] messageBodyBytes = "Hello,world! ". getBytes();
channel.basicPublish(exchangeName , routingKey , null , messageBodyBytes);

为了更好地控制发送,可以使用mandatory 这个参数, 或者可以发送一些特定属性的信息:

channel.basicPub1ish(exchangeName, routingngKey, mandatory, MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes) ;

上面这行代码发送了一条消息,查看源码(MessageProperties.PERSISTENT_TEXT_PLAIN)可以发现这条消息的投递模式( delivery mode ) 设直为2 ,即消息会被持久化(即存入磁盘)在服务器中。同时这条消息的优先级( priority )设置为0 , content-type为" text/plain" 。可以自己设定消息的属性:

channe1.basicPub1ish(exchangeName, routingKey ,
new AMQP.BasicProperties.Builder()
.contentType("text/plain")
.deliveryMode(2)
.priority(1)
.userId("hidden")
.build()), messageBodyBytes) ;

也可以发送一条带有headers 的消息:

Map<String, Object> headers = new HashMap<>() ;
headers.put("loca1tion", "here");
headers.put("time", "today");
channe1.basicPublish(exchangeName,routingKey ,
new AMQP.BasicProperties.Builder()
.headers(headers)
.build()) ,
messageBodyBytes) ;

还可以发送一条带有过期时间(expiration ) 的消息:

channe1.basicPub1ish(exchangeName, routingKey,
new AMQP.BasicProperties.Bui1der()
.expiration("60000")
.build()) ,
messageBodyBytes);

以上只是举例,由于篇幅关系,这里就不一一列举所有的可能情形了。对于basicPublish而言,有几个重载方法:

1.void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;
2.void basicPublish(String exchange, String routingKey, boolean mandatory, BasicProperties props, byte[] body)
            throws IOException;
3.void basicPublish(String exchange, String routingKey, boolean mandatory, boolean immediate, BasicProperties props, byte[] body)
            throws IOException;

对应的具体参数解释如下所述:

exchange: 交换器的名称, 指明消息需要发送到哪个交换器中。如果设置为空字符串,则消息会被发送到RabbitMQ 默认的交换器中。

routingKey: 路由键,交换器根据路由键将消息存储到相应的队列之中。

props: 消息的基本属性集, 其包含14 个属性成员,分别有contentType 、contentEncoding 、headers ( Map<String , Object>) 、deliveryMode 、priority 、correlationId 、replyTo 、expiration 、messageld、timestamp 、type 、userld 、appld、clusterld。其中常用的几种都在上面的示例中进行了演示。

body: 消息体( payload ) ,真正需要发送的消息。

mandatory 和 immediate 的详细内容会在后面说到

posted @ 2020-10-13 13:36  KILLNPE  阅读(443)  评论(0编辑  收藏  举报