Consumer类:
/**RocketMQ消费者类,在web容器启动时启动一个消费线程,详见MyListenerOnServlet
* Created by chenhaitao on 2017/9/28.
*/
public class Consumer {
public void testConsume(){
DefaultMQPushConsumer consumer =
new DefaultMQPushConsumer("PushConsumer_ChenHT_Test");
consumer.setNamesrvAddr("192.168.20.31:9876");
try {
//订阅PushTopic下Tag为push的消息
consumer.subscribe("PushTopicChenhaitao", "push");
//程序第一次启动从消息队列头取数据
System.out.println("开始监听PushTopicChenhaitao频道的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());
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
}
);
consumer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Producer类:
/**RocketMQ生产者类,在请求接口时访问该类的消息推送,以便于消费者进程的消费。
* Created by chenhaitao on 2017/9/28.
*/
public class Producer {
public void test(String msgString){
DefaultMQProducer producer = new DefaultMQProducer("Producer_ChenHT_Test");
producer.setNamesrvAddr("192.168.20.31:9876");
try {
producer.start();
Message msg = new Message("PushTopicChenhaitao",
"push",
"1",
msgString.getBytes());
SendResult result = producer.send(msg);
System.out.println("发送端:"+"id:" + result.getMsgId() +
" result:" + result.getSendStatus());
} catch (Exception e) {
e.printStackTrace();
}finally{
producer.shutdown();
}
}
}
Service层:
public void testRocketMQForProduceAndConsume(String msg){
Producer producer = new Producer();
producer.test(msg);
}
Controller层:
@RequestMapping("/t08")
public String test08(@RequestParam("msg") String msg){
testService.testRocketMQForProduceAndConsume(msg);
return "完成";
}
http://localhost:8080/test/t08?msg=郭振源吃大屁
会在控制台出现以下内容
发送端:id:C0A8141F00002A9F0000000012DD1A42 result:SEND_OK
接收到的消息是:MessageExt [queueId=0, storeSize=155, queueOffset=2, sysFlag=0, bornTimestamp=1506581395974, bornHost=/192.168.90.239:55677, storeTimestamp=1506581396051, storeHost=/192.168.20.31:10911, msgId=C0A8141F00002A9F0000000012DD1A42, commitLogOffset=316480066, bodyCRC=681917820, reconsumeTimes=0, preparedTransactionOffset=0, toString()=Message [topic=PushTopicChenhaitao, flag=0, properties={MIN_OFFSET=0, MAX_OFFSET=3, KEYS=1, WAIT=true, TAGS=push}, body=18]]
参考监听器:
@Configuration
@WebListener
public class MyListenerOnServlet implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("ServletContext容器初始化了。。。");
/*Thread threadOnRedis = new TestSubscribe();
threadOnRedis.start();*/
Consumer consumer = new Consumer();
consumer.testConsume();
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("ServletContext容器销毁了。。。");
}
}
随便玩了一下,还不知道具体应用场景以及更深层次的用法,略略略。。。