官网:http://rocketmq.apache.org/docs/quick-start/
1、web直接使用
引入依赖:
org.apache.rocketmq
rocketmq-client
4.1.0-incubating
生产者:
public static void main(String[] args) {
DefaultMQProducer producer = new DefaultMQProducer(“shanweb”);
producer.setNamesrvAddr(“10.0.16.181:9876”);
try {
producer.start();
Message msg = new Message("PushTopic",
"push",
"1",
"Just for test.".getBytes());
SendResult result = producer.send(msg);
System.out.println("id:" + result.getMsgId() +
" result:" + result.getSendStatus());
msg = new Message("PushTopic",
"push",
"2",
"Just for test.".getBytes());
result = producer.send(msg);
System.out.println("id:" + result.getMsgId() +
" result:" + result.getSendStatus());
msg = new Message("PushTopic",
"push",
"1",
"Just for test.".getBytes());
result = producer.send(msg);
System.out.println("id:" + result.getMsgId() +
" result:" + result.getSendStatus());
} catch (Exception e) {
e.printStackTrace();
}finally{
producer.shutdown();
}
}
消费者:
public static void main(String[] args) {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(“PushConsumer”);
consumer.setNamesrvAddr(“10.0.16.181:9876”);
try {
//订阅PushTopic下Tag为push的消息
consumer.subscribe(“PushTopic”, “push”);
//程序第一次启动从消息队列头取数据
consumer.setConsumeFromWhere(
ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
consumer.registerMessageListener(new MessageListenerConcurrently() {
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext Context) {
Message msg = list.get(0);
// System.out.println(msg.toString());
System.out.println(“thread========”+Thread.currentThread().getName());
String brokerNamer = Context.getMessageQueue().getBrokerName();
int queueId = Context.getMessageQueue().getQueueId();
String topic1 = Context.getMessageQueue().getTopic();
System.out.println(“brokerNamer:”+brokerNamer+",queueId:"+queueId+",topic1:"+topic1);
String topic = msg.getTopic();
System.out.println("topic = " + topic);
byte[] body = msg.getBody();
System.out.println("body: " + new String(body));
String keys = msg.getKeys();
System.out.println("keys = " + keys);
String tags = msg.getTags();
System.out.println("tags = " + tags);
System.out.println("-----------------------------------------------");
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
}
);
consumer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
2、springboot使用:
生产者:
@Service
public class ProducerService {
private static Logger log = LoggerFactory.getLogger(ProducerService.class);
private DefaultMQProducer producer;
@PostConstruct
private void initMQProducer(){
producer = new DefaultMQProducer(“producerGroupName”);
producer.setRetryTimesWhenSendFailed(3);//发送失败重试次数
producer.setNamesrvAddr(“mq1.kzkt.com:9876”);
try{
producer.start();
}
catch(MQClientException e)
{
//e.printStackTrace();
log.error(“CenterMqSender start failed”, e);
}
}
public boolean sent(String Topic, String tag, String keys, String msg, DelayTime delayTime){
boolean ret = false;
try{
Message m = new Message(Topic,
tag,
keys,
msg.getBytes(StandardCharsets.UTF_8));
if(delayTime!=null){
m.setDelayTimeLevel(delayTime.getCode());
}
SendResult sendRes = producer.send(m,2000);
if(SendStatus.SEND_OK ==sendRes.getSendStatus()){
ret = true;
}else{
log.error("Send message to MQ: " + msg + ", not OK: " + sendRes.toString());
ret = false;
}
}catch(Exception e){
//e.printStackTrace();
log.error("CenterMqSender start failed", e);
}
return ret;
}
@PreDestroy
private void shutDownProducer(){
if(producer!=null){
log.info("=================shutDownProducer=");
producer.shutdown();
}
}
}
消费者:
@Service
public class ConsumerService {
private static Logger log = LoggerFactory.getLogger(ConsumerService.class);
@PostConstruct
public void addListener() throws MQClientException {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(“producerGroupName”);
consumer.setNamesrvAddr(“mq1.kzkt.com:9876”);
consumer.setMessageModel(MessageModel.CLUSTERING);
consumer.subscribe(“topic”, “*”);
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
final Date now = new Date();
consumer.registerMessageListener(new MessageListenerConcurrently() {
@Override
public ConsumeConcurrentlyStatus consumeMessage(List msgs, ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
String msgId = msg.getMsgId();
try {
String content = new String(msg.getBody());
log.debug("msg:{},{},{} ,{}",content,context.getMessageQueue().getBrokerName(),context.getMessageQueue().getQueueId(),msgId);
onMessage(content);
} catch (Exception e) {
log.error("MessageNotifyExpiredMq eror ",e);
}
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
consumer.start();
log.info("MessageNotifyExpiredMq Started.");
}
public void onMessage(String content){
log.info("==============content"+content);
}
}
冲哥的消费rocketmq,防止出现启动报错,队列信息丢失
@Service
@RocketMQMessageListener(topic = “test”, consumerGroup = “test-group”)
@Log4j2
public class RocketMqServiceMa implements RocketMQListener<Map<String, Object>> {
@Override
public void onMessage(Map<String, Object> map) {
log.info(“消费:{}”,map);
}
}
冲哥的发送消息
@Service
public class SendMsg {
@Autowired
private RocketMQTemplate rocketMQTemplate;
public void syncSend(){
Map<String, Object> map = Maps.newHashMap();
//发送同步消息
map.put(“msg”, “syncSend”);
SendResult sendResult = rocketMQTemplate.syncSend(“test”, map);
System.out.println(String.format("***********syncSend msg %s sendResult=%s %n",map, sendResult));
map.put("msg", "syncSendOrderly");
//发送同步顺序消息
sendResult = rocketMQTemplate.syncSendOrderly(“test”, map, “123”);
System.out.println(String.format("***********syncSendOrderly msg %s sendResult=%s %n",map, sendResult));
//发送同步延迟消息
map.put("msg", "syncSendDelayLevel");
sendResult = rocketMQTemplate.syncSendDelayLevel("test", map, 2);
System.out.println(String.format("***********syncSendDelayLevel msg %s sendResult=%s %n",map, sendResult));
//发送异步消息
map.put("msg", "asyncSend");
//发送异步消息
map.put("msg", "asyncSend");
rocketMQTemplate.asyncSend("test", map, new SendCallback() {
public void onSuccess(SendResult var1) {
System.out.printf("async onSucess SendResult=%s %n", var1);
}
public void onException(Throwable var1) {
System.out.printf("async onException Throwable=%s %n", var1);
}
});
//发送最多一次消息(异步,无返回值)
map.put(“msg”, “sendOneWay”);
rocketMQTemplate.sendOneWay(“test”, map);
}
}