集成 Spring
Maven 依赖
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.3.2</version>
</dependency>
程序设计
- 参数配置在配置文件中,然后通过
@Value
注解引人,如NameServer
的地址、GoupName
名称和Topic
名称等 - 发送消息和消费消息的功能封装成 Service,被其他程序使用
- Producer和Consumer 的初始化比较慢,不建议每发一个消息或者消费一个消息就启动和注销对应的Object
- 初始化操作代码写到
@PostConstruct
函数里 - 把关闭操作代码写到
@PreDestroy
函数里
- 使用 Consumer 的方式和使用Producer 类似,但是具体设置会因为使用的具体Class 不同而不同。调用shutdown 函数是必要的,否则可能因为程序被强制关闭而丢消息。
代码实例
@Service
public class ProducerService {
private DefaultMQProducer producer = null;
@PostConstruct
public void initMQProducer() {
producer = new DefaultMQProducer("producerGroupName");
producer.setNamesrvAddr("");
producer.setRetryTimesWhenSendFailed(3);
try {
producer.start();
} catch (MQClientException e) {
e.printStackTrace();
}
}
public void send(String topic, String msg) {
Message message = new Message(topic, "", "", msg.getBytes());
try {
producer.send(message);
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
}
@PreDestroy
public void shutDownProducer() {
if (producer != null) {
producer.shutdown();
}
}
}
集成 Spring Boot
通过Spring Messaging 方式使用
- 和Spring 集成,是直接使用 RocketMQ 的方式,直接使用API方法,比较简单,不够灵活
- SpringBoot 对于消息传递,有统一的接口模板,基于这个模板可以对接各种类型的消息通信组件,比如Kafka 、RabbitMQ、RocketMQ等。使用这种方式,其基于不同消息队列收发消息的代码类似,方便在不同的消息队列间切换
Maven 依赖
- 这个依赖可以在GitHub 上下载源码,本地构建
- rocketmq-spring
<dependency>
<groupId>org.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
配置与设计
- 默认配置参数与自动配置类
- 配置参数
org.rocketmq.starter.configuration.RocketMQProperties
- 自动配置类
org.rocketmq.starter.configuration.RocketMQAutoConfiguration
- 配置例子
spring:
rocketmq:
name-server:
producer:
group: my_group
retry-times-when-send-failed: 3
retry-times-when-send-async-failed: 3
compress-msg-body-over-howmuch: 4096
send-msg-timeout: 300000
max-message-size: 4194304
retry-another-broker-when-not-store-ok: true
consume-thread-min: 20
consume-thread-max: 64
代码设计
Producer
代码实例
@Service
public class ProducerServiceBoot {
@Resource
private RocketMQProducerTemplate producerTemplate;
/**
* 简单使用
*
* @throws InterruptedException
* @throws RemotingException
* @throws MQClientException
* @throws MQBrokerException
*/
public void send() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
Message message = new Message("topic", "msg context".getBytes(Charset.forName("utf-8")));
producerTemplate.send(message);
producerTemplate.start();
}
/**
* MessageQueueSelector
*
* @throws Exception
*/
public void send2() throws Exception {
Message message = new Message("topic", "msg context".getBytes(Charset.forName("utf-8")));
MessageProxy messageProxy = new MessageProxy();
messageProxy.setMessage(message);
messageProxy.setMessageQueueSelector(new MessageQueueSelector() {
@Override
public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
return list.get(0);
}
});
producerTemplate.send(messageProxy);
producerTemplate.start();
}
/**
* 异步
*
* @throws Exception
*/
public void send3() throws Exception {
Message message = new Message("topic", "msg context".getBytes(Charset.forName("utf-8")));
MessageProxy messageProxy = new MessageProxy();
messageProxy.setSendCallback(new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
SendStatus sendStatus = sendResult.getSendStatus();
switch (sendStatus) {
case SEND_OK:
break;
case FLUSH_DISK_TIMEOUT:
break;
case FLUSH_SLAVE_TIMEOUT:
break;
case SLAVE_NOT_AVAILABLE:
break;
}
}
@Override
public void onException(Throwable e) {
}
});
producerTemplate.send(messageProxy);
producerTemplate.start();
}
}
Consumer
代码实例:使用@RocketMQMessageListener
注解
@SpringBootApplication
public class ConsumerApplication{
public static void main(String[] args){
SpringApplication.run(ConsumerApplication.class, args);
}
@Slf4j
@Service
@RocketMQMessageListener(topic = "test-topic-1", consumerGroup = "my-consumer_test-topic-1")
public class MyConsumer1 implements RocketMQListener<String>{
public void onMessage(String message) {
log.info("received message: {}", message);
}
}
@Slf4j
@Service
@RocketMQMessageListener(topic = "test-topic-2", consumerGroup = "my-consumer_test-topic-2")
public class MyConsumer2 implements RocketMQListener<OrderPaidEvent>{
public void onMessage(OrderPaidEvent orderPaidEvent) {
log.info("received orderPaidEvent: {}", orderPaidEvent);
}
}
}
参考
- Apache RocketMQ 官网
- Best Practice For Broker
- RocketMQ-Spring
- rocketmq-spring-boot-samples
- rocketmq-spring