只介绍入门使用,不说明原理。
一、需要linux系统,
JDK1.7+
rocketmq http://download.csdn.net/detail/zhangscheng922/9873034
二、配置JAVA_HOME
在 /etc/profile 文件中添加如下,路径需按实际情况
export JAVA_HOME=/usr/local/java
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
三、由于是测试,需要修改RocketMq的JVM参数。默认需要4G内存,修改 bin目下runserver.sh和runbrocker.sh为如下
JAVA_OPT="${JAVA_OPT} -server -Xms512m -Xmx512m -Xmn512 -XX:PermSize=128m -XX:MaxPermSize=320m"
四、启动namesvr和brocker
# nohup sh mqnamesrv &
# nohup sh mqbroker -n "192.168.137.100:9876" -c ../conf/2m-noslave/broker-a.properties>broker.out &
192.168.137.100:9876 ip地址为虚拟机ip,端口9876为默认的。其它nohup命令详解可参考 http://www.cnblogs.com/zq-inlook/p/3577003.html
启动完成后使用jps命令查看 namesrv和brocker是否都已启动。
五、关闭namesrv和brocker
# sh mqshutdown namesrv
# sh mqshutdown broker
六、示例代码(java)
需要rocketmq的jar包,可以去阿里的maven库下一个
生产者
public class Producer {
public static void main(String[] args) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
DefaultMQProducer producer=new DefaultMQProducer("group");
producer.setNamesrvAddr("192.168.137.200:9876");
producer.start();
Message msg=null;
for (int i = 0; i < 100; i++) {
msg=new Message("orders",("orders"+i).getBytes());
SendResult result = producer.send(msg);
System.out.println(msg);
System.out.println(result);
Thread.sleep(500);
}
}
}
消费者
public class PushConsumer {
public static void main(String[] args) throws MQClientException {
DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("consumer");
consumer.setNamesrvAddr("192.168.137.200:9876");
//开始订阅指定topic和tag的消息
consumer.subscribe("orders", null);
//设置从什么位置开始读取消息
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
//注册监听器
consumer.registerMessageListener(new MessageListenerConcurrently() {
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext arg1) {
MessageExt msg = list.get(0);
System.out.println(new String(msg.getBody()));
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
//开始消费
consumer.start();
}
}