发送消息
可以使用如下方式发送消息
channel.basicPublish(exchangeName, routingKey, null, "Hello World".getBytes());Copied!
1
为了更好的控制发送,可以使用 mandatory 参数,或则发送一些特定属性的信息:
channel.basicPublish(exchangeName, routingKey, mandatory, MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);Copied!
1
PERSISTENT_TEXT_PLAIN:消息投递模式(delivery mode = 2),消息会被持久化。同时消息的优先级(priority) 设置为 1。 content-type = “text/.plain”
#自定义消息属性
channel.basicPublish(exchangeName, routingKey,new AMQP.BasicProperties.Builder().contentType("text/plain").deliveryMode(2).priority(1).userId("hidden").build(),messageBodyBytes);Copied!
1
2
3
4
5
6
7
8
9
#发送带有 headers 的消息
final HashMap<String, Object> headers = new HashMap<>();headers.put("localtion", "here");headers.put("time", "today");channel.basicPublish(exchangeName, routingKey,new AMQP.BasicProperties.Builder().headers(headers).build(),messageBodyBytes);Copied!
1
2
3
4
5
6
7
8
9
#发送过期(expiration)消息
channel.basicPublish(exchangeName, routingKey,new AMQP.BasicProperties.Builder().expiration("60000").build(),messageBodyBytes);Copied!
1
2
3
4
5
6
#完整参数说明
上面是几个常用的消息发送,他们都有一个完整参数的方法
void basicPublish(String exchange, String routingKey, boolean mandatory, BasicProperties props, byte[] body)throws IOException;Copied!
1
2
- exchange:交换器名称,如果为空,则会发送到 RabbitMQ 默认的交换器中
- routingKey:路由键
- mandatory:该内容请参阅下一章
- props:消息的基本属性集,有如下 14 个属性成员
- contentType
- contentEncoding
- headers(Map
) - deliveryMode
- priority
- correlationId
- replyTo
- expiration
- messageId
- timestamp
- type
- userId
- body:消息体(payload)
