After comparing the RABBITMQ,APACHEMQ, the discovery is still rocketmq easy to use.
why easy to use, Baidu Check all know. Don't say crap, just say it.
Linux Installation:
1, the need for software (installation-free version)
Download Address
[release download Address] (https://github.com/apache/incubator-rocketmq/releases)
https://github.com/ Apache/incubator-rocketmq/releases
Rocketmq-all-4.0.0-incubating-bin-release.zip
2. Install JDK Environment
No more. 3, start namesrv
Go under the bin of the installation folder
Use command: Nohup sh mqnamesrv &
View Nohup Log
Error message found caused BY:JAVA.NET.UNKNOWNHOSTEXCEPTION:SMKZFBWEB02: unknown name or service
View files/etc/hosts and/etc/hostname at this time
Found the problem, my production server hostname was changed by the administrator, but did not add to the hosts corresponding list, so the error. Java.net.UnknownHostException
We modify the/etc/hosts file
Start again
The Name Server boot success. Serializetype=json 4, start broker
Using the command nohup sh mqbroker-n "1273.0.0.1:9876" &
View Log
This is said to be # Native memory allocation (malloc) failed to allocate 8589934592 the for bytes committing. The memory is not enough.
View configuration Files
The runbroker.sh file is the broker's startup file
runserver.sh file is Namesev boot file
View
It is found that their default memory requirements are large, so according to their own server configuration to reduce some of the configuration
It's OK to start after the configuration is ready.
Package COM.CAT.COMMON.ROCKETMQ;
Import java.util.Properties;
Import Org.apache.log4j.Logger;
Import Com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
Import com.alibaba.rocketmq.client.exception.MQClientException;
Import Com.alibaba.rocketmq.client.producer.DefaultMQProducer;
Import Com.alibaba.rocketmq.client.producer.SendResult;
Import Com.alibaba.rocketmq.common.message.Message;
Import Com.alibaba.rocketmq.common.protocol.heartbeat.MessageModel;
Import Com.cat.common.lang.RDate;
Import com.cat.common.lang.RString;
Import Com.cat.common.lang.RUuid;
Import Com.cat.common.properties.PropertiesUtil;
/** * ROCKETMQ does not guarantee that messages will not repeat, if your business needs to ensure strict not repeat messages, you need to be in the business side of the heavy. * The autocreatetopicenable should be turned off on the line, that is, set to False in the configuration file ...
The consequence: all future topic messages will be sent to this broker to achieve the goal of load balancing. * API 3.6.2.Final jar Pack is a problem, not recommended, currently used, 3.5.9JAR can * use 3.6.2jar problem is, the producer sends the message, consumer consumption, not to the message status synchronization to broken, cause consumers restart, or will be again
News, repeat consumption. * Cluster consumer = Multiple consumers are cluster consumers, subscribe to the same message, broken will distribute the message evenly to all cluster consumers * different cluster consumers (specified the wrong group name), subscribe to the same topic, will receive thisTopic message * Broadcast consumer = after multiple broadcast consumers subscribe to the same message, each broadcast consumer receives the message * the same JVM can only have a unique group name + instance name producer, or consumer, so the following producer and consumer instance names are specified with UUID * @ Author Luoyang * */public class rocketmqutils{private static Logger _logger = Logger.getlogger (rocketmqutils.class
);
private static final Logger _socketlog = Logger.getlogger ("Socketmqsendmessage");
private static defaultmqproducer producer;
private static Defaultmqpushconsumer consumer;
private static Defaultmqpushconsumer Broadconsumer;
private static Object obj = null;
private static properties properties = NULL; private static void InitProperties () {if (null = = properties) {Properties = new properties ();//STR
ing path = rsystemconfig.home_path + "Socketmq.properties";
String Path = "D://socketmq.properties";
Properties = Propertiesutil.getinstance (). getProperties (path);
_logger.info ("Init socketmq.properties success."); } public static void SendMessage (String tOPIc, String messagecontent) {try{if (Rstring.isblank (topic)) {
Return
} if (null = = producer) {getproducer ();
} _logger.info ("SendMessage topic=" + topic + "messagecontent=" + messagecontent); _socketlog.info (Rstring.format ("{0}, SendMessage topic={1}, Messagecontent={2}", Rdate.getcurrenttimestr () + "|",
Topic, messagecontent));
Topic, MSG = new Message (topic, messagecontent.getbytes ());
Sendresult Sendresult = producer.send (msg);
_logger.info ("SendMessage sendresult=" + sendresult.tostring ()); }catch (Exception e) {_socketlog.error (Rdate.getcurrenttimestr () + "|
SendMessage topic= "+ topic +" messagecontent= "+ messagecontent, E); }/** * Send message, tool class * * @param topic * @param message content * @param repeattime if sending fails, Allow repeat send number, after each failure interval 200ms continue to send * * * PublIC static void SendMessage (String topic, String messagecontent,
int repeattime) {_logger.info ("SendMessage topic=" + topic + "messagecontent=" + messagecontent); _socketlog.info (Rstring.format ("{0}, SendMessage topic={1}, Messagecontent={2}", Rdate.getcurrenttimestr () + "|",
Topic, messagecontent));
if (Rstring.isblank (topic)) {return;
} if (null = = producer) {getproducer ();
Boolean result = false; for (int i = 1; I <= repeattime i++) {try{message msg = new Message (topic, messagecontent.getbyte
s ());
Sendresult Sendresult = producer.send (msg);
_logger.info ("SendMessage sendresult=" + sendresult.tostring ());
result = true;
}catch (Exception e) {e.printstacktrace (); _logger.error ("Send Message Have exception" + E + "topic=" + topic + "messagecontent=" + MessageContent);
} _logger.info ("SendMessage topic=" + topic + "messagecontent=" + messagecontent);
if (!result) {try{thread.sleep (200);
}catch (interruptedexception e) {e.printstacktrace (); _logger.error ("Send Message Have exception" + E + "topic=" + topic + "messagecontent=" + messagecontent + "Repeat Time="
+ i);
} continue;
}else{break; }} private static synchronized Defaultmqproducer Getproducer () {if (null!= producer) {Retur
n producer;
} initproperties ();
Within a JVM, there is only one producer instance with the same producergroup name.
Producer = new Defaultmqproducer (rtopicconstants.product_group);
Producer.setnamesrvaddr (Properties.getproperty ("namesrv_addr"));
Producer.setinstancename (Ruuid.makeuuid ());
try{//producer opens Producer.start (); Close the producer Runtime.getruntim when the container is closedE (). Addshutdownhook (New Thread (new Runnable () {public void run () {_logger.info ("Getproducer" +
"... producer.shutdown ..."........;
Producer.shutdown ();
}
})); _logger.info ("Getproducer init product success.")
DATA[NAMESRVADDR={0}] "+ Properties.getproperty (" namesrv_addr "));
}catch (mqclientexception e) {e.printstacktrace ();
_logger.error ("Getproducer have exception" + E);
return producer;
public static Defaultmqpushconsumer Getconsumer () {if (null!= obj) {return consumer;
} initconsumer ();
return consumer;
public static Defaultmqpushconsumer Getbroadconsumer () {if (null!= obj) {return broadconsumer;
} initconsumer ();
return broadconsumer;
private static synchronized void Initconsumer () {try{if (null = obj) {initproperties (); Consumer = new DefauLtmqpushconsumer (Rtopicconstants.consumer_group);
Consumer.setnamesrvaddr (Properties.getproperty ("namesrv_addr"));
Consumer.setinstancename (Ruuid.makeuuid ());
Broadconsumer = new Defaultmqpushconsumer (rtopicconstants.broad_consumer_group);
Broadconsumer.setnamesrvaddr (Properties.getproperty ("namesrv_addr"));
Broadconsumer.setmessagemodel (messagemodel.broadcasting);
Broadconsumer.setinstancename (Ruuid.makeuuid ());
obj = new Object (); _logger.info ("Intconsumer Init consumer success.
DATA[NAMESRVADDR={0}] "+ Properties.getproperty (" namesrv_addr "));
}}catch (Exception e) {e.printstacktrace ();
_logger.error ("Initconsumer have exception" + E);
}
}
}
Package COM.CAT.COMMON.ROCKETMQ;
public class rtopicconstants{
/**
* default Cluster consumer * * Public
static final String consumer_group= " Consumergroup ";
/**
* Broadcast consumer
/public static final String broad_consumer_group= "Broadconsumergroup";
/**
* Producer Group * * Public
static final String product_group= "ProductGroup";
/**
* Default producer
*
/public static final String instancename_producer = "Producer";
/**-------UIC Message topic-------**/public
static final String luoyang= "Luoyang";
}
Producers
Package COM.CAT.COMMON.ROCKETMQ;
Import Java.util.HashMap;
Import Java.util.Map;
Import Com.cat.common.json.RJson;
Import com.cat.common.lang.RDate;
public class demoproduct{public
static void Main (string[] args) {
try{for
(int i = 0; i < 5; i++) {
map& Lt String, object> m = new hashmap<string, object> ();
M.put ("name", i+ "1");
M.put ("Age", ten);
M.put ("Address", i+ "Hangzhou Jinjiang with Card");
String msg = Rjson.getjson (m);
Rocketmqutils.sendmessage (Rtopicconstants.luoyang, msg);
Thread.Sleep (1000);
System.out.println (RDATE.GETCURRENTTIMESTR () + ", Production send Message" +i);
}
catch (Exception e) {
//TODO auto-generated catch block
e.printstacktrace ();
}
}
}
Consumers
Package COM.CAT.COMMON.ROCKETMQ;
Import java.util.List;
Import Com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
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.client.exception.MQClientException;
Import Com.alibaba.rocketmq.common.message.MessageExt;
public class democustom{public static void Initconsumer () {try{System.out.println ("Open cluster Consumer 1:");
Defaultmqpushconsumer consumer = Rocketmqutils.getconsumer ();
Consumer.subscribe (Rtopicconstants.luoyang, "*"); Consumer.registermessagelistener (New messagelistenerconcurrently () {public Consumeconcurrentlystatus consumeMe Ssage (list<messageext> msgs, Consumeconcurrentlycontext
Context) { try{messageext msg = msgs.get (0);
String data = new String (Msg.getbody ());
if (Msg.gettopic (). Equals (Rtopicconstants.luoyang)) {System.out.println ("The cluster consumer receives the message:" + data);
}}catch (Exception e) {e.printstacktrace ();
After a while resend, can judge the time to retry return consumeconcurrentlystatus.reconsume_later;
///Successful return consumeconcurrentlystatus.consume_success based on business logic;
}
});
Open consumption Consumer.start ();
}catch (Exception e) {e.printstacktrace (); }/** * Register broadcast mode message * @throws mqclientexception/public static void Initbroadconsumer () t
Hrows mqclientexception{System.out.println ("Open broadcast consumer");
Defaultmqpushconsumer Broadconsumer = Rocketmqutils.getbroadconsumer (); Broadconsumer.subscrIbe (Rtopicconstants.luoyang, "*"); Broadconsumer.registermessagelistener (New messagelistenerconcurrently () {public Consumeconcurrentlystatus consum Emessage (list<messageext> msgs, Consumeconcurrentlycontext
Context) {try{Messageext msg = msgs.get (0);
String data = new String (Msg.getbody ()); Data resolution//Sync Configuration Center Data if (Msg.gettopic (). Equals (Rtopicconstants.luoyang)) {Sy
STEM.OUT.PRINTLN ("The broadcast consumer receives the message:" + data);
}}catch (Exception e) {e.printstacktrace ();
return consumeconcurrentlystatus.reconsume_later;
return consumeconcurrentlystatus.consume_success;
}
});
Broadconsumer.start ();
public static void Main (string[] args) {try{initconsumer ();
Initbroadconsumer (); }catch (exception e) {e.printstacktrace ();
}
}
}
For producers
Within a JVM, there is only one producer instance with the same producergroup name.
producer = new Defaultmqproducer (rtopicconstants.product_group);
Producer.setnamesrvaddr (Properties.getproperty ("namesrv_addr"));
Producer.setinstancename (Ruuid.makeuuid ());
Group name +instancename must be unique within the same JVM.
Otherwise it will be an error. So the instancename I set here is the UUID.
For consumers
There are two kinds, one is broadcast, one is cluster
Broadcast mode of consumer information will not be stored in the broken, directly sent to consumers, all broadcast consumers will consume the message.
Cluster mode, if a group of consumers groupname consistent, it is defined as the same consumer cluster. It is important to ensure that the instancename of the consumer within a JVM is unique.
Average consumer message for cluster consumers in the same group
And if it is a cluster consumption, then all consumers of cluster consumption must subscribe to the same topic, or they will complain