本文所介绍环境为win7环境下运行, 从官方github中(https://github.com/alibaba/RocketMQ)下载RocketMQ-master.zip,版本为v3.5.8,解压并进入根目录,运行命令install.bat, 安装完成后进入目录\target\alibaba-rocketmq-broker\alibaba-rocketmq\bin,打开两个命令行窗口,分别使用以下命令启动rocketmq

启动nameserver
mqnamesrv.exe
启动broker
mqbroker -n 127.0.0.1:9876

1、编写pom.xml,

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hode</groupId>
<artifactId>rocketmq</artifactId>
<version>0.0.1-SNAPSHOT</version> <properties>
<spring.version>4.3.2.RELEASE</spring.version>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<rocketmq.version>3.2.6</rocketmq.version>
<slf4j.version>1.7.12</slf4j.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency> <dependency>
<groupId>com.alibaba.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>${rocketmq.version}</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin> </plugins>
</build> </project>

2、编写spring配置文件applicationContext-consumer.xml,applicationContext-producer.xml以及log4j.properties,内容如下

applicationContext-consumer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> <bean id="producer" class="com.hode.rocketmq.Consumer" init-method="init" destroy-method="destroy">
<constructor-arg name="consumerGroup" value="rocketmq-test" />
<constructor-arg name="namesrvAddr" value="127.0.0.1:9876" />
<constructor-arg name="instanceName" value="test" />
<constructor-arg name="topic" value="testTopic" />
<constructor-arg name="messageListener" ref="messageListener" />
</bean> <bean id="messageListener" class="com.hode.rocketmq.StringMessageListener" /> </beans>

applicationContext-producer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> <bean id="producer" class="com.hode.rocketmq.Producer" init-method="init" destroy-method="destroy">
<constructor-arg name="producerGroup" value="rocketmq-test" />
<constructor-arg name="namesrvAddr" value="127.0.0.1:9876" />
<constructor-arg name="instanceName" value="test" />
</bean> </beans>

log4j.properties

log4j.rootLogger=INFO,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%-4r %d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n log4j.logger.com.hode=DEBUG

3、编写类StringMessageListener.java,Producer.java,Consumer.java

StringMessageListener.java

import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.common.message.MessageExt; public class StringMessageListener implements MessageListenerConcurrently{ private Logger log = Logger.getLogger(getClass()); @Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,ConsumeConcurrentlyContext context) {
for (MessageExt msg : msgs) {
log.info("msg : " + new String(msg.getBody()));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
} }

Producer.java

import org.apache.log4j.Logger;

import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer; /**
* 生产
*/
public class Producer { protected Logger log = Logger.getLogger(getClass()); private String producerGroup; private String namesrvAddr; private String instanceName; private DefaultMQProducer producer; public DefaultMQProducer getProducer() {
return producer;
} public Producer(String producerGroup,String namesrvAddr,String instanceName){
this.producerGroup = producerGroup;
this.namesrvAddr = namesrvAddr;
this.instanceName = instanceName;
} public void init() throws MQClientException{
log.info("start init DefaultMQProducer...");
producer = new DefaultMQProducer(producerGroup);
producer.setNamesrvAddr(namesrvAddr);
producer.setInstanceName(instanceName);
producer.start();
log.info("DefaultMQProducer init success.");
} public void destroy(){
log.info("start destroy DefaultMQProducer...");
producer.shutdown();
log.info("DefaultMQProducer destroy success.");
} }

Consumer.java

import org.apache.log4j.Logger;

import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.common.consumer.ConsumeFromWhere; public class Consumer { private Logger log = Logger.getLogger(getClass()); private DefaultMQPushConsumer consumer; private String consumerGroup; private String namesrvAddr; private String instanceName; private String topic; private MessageListenerConcurrently messageListener; public Consumer(String consumerGroup,String namesrvAddr,String instanceName,String topic,MessageListenerConcurrently messageListener){
this.consumerGroup = consumerGroup;
this.namesrvAddr = namesrvAddr;
this.instanceName = instanceName;
this.topic = topic;
this.messageListener = messageListener;
} public void init() throws Exception{
log.info("start init DefaultMQPushConsumer...");
consumer = new DefaultMQPushConsumer(consumerGroup);
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); //从队列头部开始消费
consumer.setNamesrvAddr(namesrvAddr);
consumer.setInstanceName(instanceName);
consumer.subscribe(topic, "*");
consumer.registerMessageListener(messageListener);
consumer.start();
log.info("DefaultMQPushConsumer init ok.");
} public void destroy(){
log.info("start destroy DefaultMQPushConsumer...");
consumer.shutdown();
log.info("DefaultMQPushConsumer destroy success.");
} public DefaultMQPushConsumer getConsumer() {
return consumer;
} }

4、编写测试类

ProducerTest.java

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendCallback;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message; public class ProducerTest { private static Logger log = Logger.getLogger(ProducerTest.class); private static ApplicationContext context; public static void main(String[] args) throws Exception{
context = new ClassPathXmlApplicationContext("classpath:applicationContext-producer.xml");
Producer producer = context.getBean(Producer.class);
DefaultMQProducer p = producer.getProducer(); String message = "test messgae"+new Date();
Message msg = new Message("testTopic",message.getBytes());
log.info(message);
p.send(msg, new SendCallback(){ @Override
public void onSuccess(SendResult sendResult) {
log.info(sendResult.getSendStatus().name());
log.info("onSuccess"); producer.destroy();
} @Override
public void onException(Throwable e) {
log.error("onException");
}
}); } }

ConsumerTest.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class ConsumerTest { private static ApplicationContext context; public static void main(String[] args) throws Exception{
context = new ClassPathXmlApplicationContext("classpath:applicationContext-consumer.xml");
Consumer consumer = context.getBean(Consumer.class); Thread.sleep(20*1000); System.out.println("end");
consumer.destroy();
} }

分别运行生产端及消费端完成测试,结束。

Spring + RocketMQ使用的更多相关文章

  1. 问题排查之'org.apache.rocketmq.spring.starter.core.RocketMQTemplate' that could not be found.- Bean method 'rocketMQTemplate' in 'RocketMQAutoConfiguration' not loaded.

    背景 今天将一个SpringBoot项目的配置参数从原有的.yml文件迁移到Apollo后,启动报错“Bean method 'rocketMQTemplate' in 'RocketMQAutoCo ...

  2. 如何在优雅地Spring 中实现消息的发送和消费

    本文将对rocktmq-spring-boot的设计实现做一个简单的介绍,读者可以通过本文了解将RocketMQ Client端集成为spring-boot-starter框架的开发细节,然后通过一个 ...

  3. Spring 整合 RocketMQ

    1. 引入jar包 <!-- RocketMQ --> <dependency> <groupId>com.alibaba.rocketmq</groupId ...

  4. Spring boot实战项目整合阿里云RocketMQ (非开源版)消息队列实现发送普通消息,延时消息 --附代码

    一.为什么选择RocketMQ消息队列? 首先RocketMQ是阿里巴巴自研出来的,也已开源.其性能和稳定性从双11就能看出来,借用阿里的一句官方介绍:历年双 11 购物狂欢节零点千万级 TPS.万亿 ...

  5. Spring Cloud异步场景分布式事务怎样做?试试RocketMQ

    一.背景 在微服务架构中,我们常常使用异步化的手段来提升系统的 吞吐量 和 解耦 上下游,而构建异步架构最常用的手段就是使用 消息队列(MQ),那异步架构怎样才能实现数据一致性呢?本文主要介绍如何使用 ...

  6. Spring Cloud Alibaba(五)RocketMQ 异步通信实现

    本文探讨如何使用 RocketMQ Binder 完成 Spring Cloud 应用消息的订阅和发布. 介绍 RocketMQ 是一款开源的分布式消息系统,基于高可用分布式集群技术,提供低延时的.高 ...

  7. 通过消息总线Spring Cloud Bus实现配置文件刷新(使用Kafka或RocketMQ)

    如果需要客户端获取到最新的配置信息需要执行refresh,我们可以利用webhook的机制每次提交代码发送请求来刷新客户端,当客户端越来越多的时候,需要每个客户端都执行一遍,这种方案就不太适合了.使用 ...

  8. Spring Cloud Alibaba学习笔记(14) - Spring Cloud Stream + RocketMQ实现分布式事务

    发送消息 在Spring消息编程模型下,使用RocketMQ收发消息 一文中,发送消息使用的是RocketMQTemplate类. 在集成了Spring Cloud Stream之后,我们可以使用So ...

  9. Spring Cloud Alibaba学习笔记(11) - RocketMQ事务消息

    在Spring中,我们要实现事务,一般通过@Transactional注解实现.这在引入RocketMQ之前没有问题,但是在引入了RocketMQ之后,如果消息发送之后的业务逻辑处理发生了异常的话,这 ...

随机推荐

  1. uni-app中Vuex的引用

    //store 中 store.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vue ...

  2. hive表批处理

    对hive中的表进行批量处理,如下是一个简单的脚本 #给定一个hive数据库名,生成它的所有表的create SQL语句,并导出到文件 create_fun(){ hive -e } #显示一个表中所 ...

  3. Python连载10-os包函数(续)

    一.os包(接连载9) 1.函数:system() (1)用法:运行系统shell命令 (2)格式:os.system(系统命令) (3)返回值:打开一个shell或终端界面 (4)注意:一般是用su ...

  4. 第二章 python如何运行程序

    一.python解释器介绍 Python解释器是一种让程序运行起来的程序.实际上,解释器是代码与机器的计算机硬件之间的软件逻辑层.当Python包安装在机器上后,它包含了一些最小化的组件:一个解释器和 ...

  5. vue-resource.js的get和post的正确用法

    在网上看到人家写的vue-resource.js的get方法例子, new Vue({ el:'body', data:{ }, methods:{ get:function(){ this.$htt ...

  6. appium入门篇之desired capabilities(2)

    目录 1.appium工作原理 desired capabilities 2.准备工作 3.第一个appium脚本 获取包名和启动的activity 编写脚本 运行结果 1.appium工作原理 启动 ...

  7. a元素变成块状元素点击之后删除出现背景

    a { text-decoration: none; background: none; -webkit-tap-highlight-color: transparent; } a:hover { - ...

  8. Linux五种IO模型 ——Java学习笔记

    本文摘自网络:     1.阻塞IO(blocking IO) 在linux中,默认情况下所有的socket都是blocking,一个典型的读操作流程大概是这样: 图1 阻塞IO 当用户进程调用了re ...

  9. 最牛MongoDB灾难恢复(WiredTiger.wt文件损坏,Mongo无法启动)

    WiredTiger.wt文件是mongoDB的元数据文件,存储了其他数据库表的元数据信息.笔者最近遇到了WiredTiger.wt文件损坏的情况,MongoDB无法启动,数据库中的重要数据危在旦夕. ...

  10. TreeView虚拟化跳转

    使用ItemContainerGenerator.ContainerFromItem方法可以获取对应数据的UIElement . 但是如果使用了虚拟化技术,超出可见区域的UIElement就获取不到了 ...