ACTIVEMQ Study notes (middle) _activemq

Source: Internet
Author: User

Four, MQTT

MQTT (Messages Queuing telemetry transport, Message Queuing telemetry transmission) is an Instant Messaging protocol developed by IBM, a lightweight agent-based publish/Subscribe message Transfer Protocol that can be connected through very little code and bandwidth and remote devices. For example, through satellite and proxy connections, through dial-up and health care provider connectivity, as well as on some automation or small equipment, and due to compact, power saving, protocol overhead and efficient Shang and multiple receivers to pass information, it is also applicable to the call application device.

Using the MQTT connection ACTIVEMQ uses a point-to-point topic message model that primarily sets the header information for the MQTT protocol.


Mqttclient mqttclient = new Mqttclient ("tcp://0.0.0.0:1883", "DeviceId", New Memorypersistence ()); ①
		
Mqttconnectoptions options = new Mqttconnectoptions ();
		
Options.setcleansession (false); ②
Options.setkeepaliveinterval (30); ③
mqttclient.connect (options);< Pre name= "code" class= "Java" >mqttclient.publish ("virtualtopic/" + "DeviceId", ("Hello Virtualtopic"). GetBytes (), 1 , false); ④
Mqttcallbachmsg callback = new Mqttcallbachmsg ();
Mqttclient.setcallback (callback);
public class Mqttcallbachmsg implements mqttcallback{
@Override public
void Connectionlost (Throwable cause) { c2/>}
@Override public
void messagearrived (String topic, Mqttmessage message) throws Exception {
System.out.println (New String (Message.getpayload (), "Utf-8"));
}
@Override public
void Deliverycomplete (Imqttdeliverytoken token) {
}
}

① parameter A is the address port number of the MQTT; parameter b is the only indication of the device; parameter C has mqttdefaultfilepersistence () and memorypersistence two cases.

②false: If the subscribed client is disconnected, then the message to be pushed is saved, and if it is reconnected, the message is pushed;

True:1 represents elimination, indicating that the client is the first to connect, so the previous connection information is the message.

③ represents the response time, if the connection or send operation is not completed within this time, disconnect the TCP connection, indicating that it is offline.

④ parameter A is a topic name; parameter b is the message content; parameter c is the qos:00, which means that the <=1,01 represents at least once, that is, >=1,10 represents one time, that is, ==1; parameter d is persisted, indicating that the server wants to keep the push information. If a new subscriber appears, push the message to it. If it is not set then the push to the current subscription is released.


V. Virtual Theme (TOPIC)

As I said earlier, the message from MQTT is the topic model, but topic is a broadcast, all listeners receive a push, but in order to ensure availability, the usual number of receiving servers is deployed, which leads to a problem: A message is processed multiple times, which is clearly something we don't want to see. Happily, ACTIVEMQ has anticipated the problem: Virtual Topic. As the name suggests, its role is to topic virtual into a queue, because the characteristics of the queue is there and only one customer. This ensures that our backend handler can be received and processed only once.

The default topic name is called Virtualtopic. , the fourth Mqtt example is the virtual topic request sent; receiver listens for the queue named Consumer.*. Virtualtopic. 。

Receive code:

Activemqconnectionfactory Factorya = new Activemqconnectionfactory (Activemqconnection.default_user,
					Activemqconnection.default_password, "tcp://101.201.29.101:1889");

Queue queue = new Activemqqueue ("consumer.test.virtualtopic.*");
Activemqconnection conn = (activemqconnection) factorya.createconnection ();
Conn.start ();
Session session = Conn.createsession (false, Session.auto_acknowledge);
Messageconsumer consumer = session.createconsumer (queue);
MessageListener listener = new MessageListener () {public
void onMessage (Message message) {
try {
//string Co ntent = new String (((activemqbytesmessage) message). GetMessage (). GetContent (). GetData (), "UTF-8");
SYSTEM.OUT.PRINTLN ("=> message content:" + message.getjmsdestination (). toString ());
catch (Exception e) {
e.printstacktrace ();}}}
;
Consumer.setmessagelistener (listener);


Six, Custom Plug-ins

ACTIVEMQ is written in Java and is a spring framework, all of which can be described as highly flexible.

We can implement the custom class by inheriting his interface into a jar package into the LIB, and finally add the plug-in configuration to the Activemq.xml.

Custom Connection validation rules:

public class Authenticationcontrolbrokerplugin implements Brokerplugin {
	private Set usergroup = new hashset< Object> ();
	Public broker Installplugin (broker broker) throws Exception {return
		new Authenticationcontrolbroker (broker, usergroup); 
	} 
public class Authenticationcontrolbroker extends brokerfilter{private final copyonwritearraylist<securitycontext& Gt
    securitycontexts = new copyonwritearraylist<securitycontext> ();
    
	Private final Set UserGroup;
		Public Authenticationcontrolbroker (Broker Next,set usergroup) {super (next);
		This.usergroup = UserGroup;
	Serviceproxyfactory.init (); @Override public void Addconnection (ConnectionContext context, ConnectionInfo info) throws Exception {Securitycont
        ext s = context.getsecuritycontext ();
                try {if (s = = null) {//todo: Your custom rule usergroup.add (Info.getusername ()); s = new SecurityContext (Info.getusername ()) {@Override public set<principal> Getprinci
    				Pals () {//TODO auto-generated method stub return usergroup;
                
                }
                };
                Context.setsecuritycontext (s);
Securitycontexts.add (s);            } super.addconnection (context, info);
            catch (Exception e) {securitycontexts.remove (s);
            Context.setsecuritycontext (NULL);
        Throw e; }
	}
}

Configuration file:

<plugins><bean xmlns= "Http://www.springframework.org/schema/beans"
id= "Myplugin" class= "Your Class path" ></bean></plugins>

PostScript: The current use and thought of these, have time to carefully look at the relevant knowledge, put in the next chapter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.