CamelOne 2013June 10-11 2013Boston, MAMessaging for web andmobile with ApacheActiveMQBy Bosanac Dejan1
CamelOne 2013CamelOne2Bosanac Dejan?• Senior Sofware Engineer at RedHat• Apache ActiveMQ committer and PMC member• Co-auth...
CamelOne 2013CamelOneAgenda• Challenges of web messaging• REST vs Stomp• In-browser messaging (Ajax vs Web Sockets)• Mobil...
CamelOne 2013CamelOneMessaging for Web• Connect from any web application backend(Ruby, PHP, Python, …)• Connect directly f...
CamelOne 2013CamelOneWhat’s wrong with Http?• Nothing at all!• Ideal for simple request-reply communication• Lacks semanti...
CamelOne 2013CamelOneLimitations• Pull based protocol• Easy simple producing• There’s no concept of consumer or subscripti...
CamelOne 2013CamelOnePull Consuming• HTTP techniques• Long polling• Comet• Maintain a state• Session• ClientID7
CamelOne 2013CamelOnePush Consuming• Web Hooks – http://webhooks.org• Provide a callback (HTTP URL) to be called onevent• ...
CamelOne 2013CamelOne Camel HTTPcomponent9<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring”><route><f...
CamelOne 2013CamelOneStomp – what it is?• http://stomp.github.com• Simple Text Orientated Messaging Protocol• HTTP for the...
CamelOne 2013CamelOneStomp – basics• Very simple, so it’s easy to write clients andservers in practically any language• A ...
CamelOne 2013CamelOneStomp - Protocol• Text based headers,similar to HTTP• Can transport binarybodies• Frame command forev...
CamelOne 2013CamelOneStomp + ActiveMQ• Available transports• NIO implementation for better scalability• SSL for secure com...
CamelOne 2013CamelOneStomp Java Client• StompJMS -https://github.com/fusesource/stompjms• APIs:• JMS• Blocking• Future• Ca...
CamelOne 2013CamelOne15Stomp stomp = new Stomp("localhost", 61613);Future<FutureConnection> future = stomp.connectFuture()...
CamelOne 2013CamelOne16StompFrame frame = new StompFrame(SEND);frame.addHeader(DESTINATION, StompFrame.encodeHeader("/queu...
CamelOne 2013CamelOne17StompFrame disconnect = new StompFrame(DISCONNECT);Future<Void> disconnectFuture = connection.send(...
CamelOne 2013CamelOne18Stomp stomp = new Stomp("localhost", 61613);Future<FutureConnection> future = stomp.connectFuture()...
CamelOne 2013CamelOne19Future<StompFrame> receiveFuture = connection.receive();StompFrame frame = new StompFrame(SUBSCRIBE...
CamelOne 2013CamelOne20StompFrame received = receiveFuture.await();System.out.println(received.content());MESSAGEmessage-i...
CamelOne 2013CamelOne21StompFrame unsubscribe = new StompFrame(UNSUBSCRIBE);unsubscribe.addHeader(ID, id);Future<Void> uns...
CamelOne 2013CamelOne22StompFrame disconnect = new StompFrame(DISCONNECT);Future<Void> disconnectFuture = connection.send(...
CamelOne 2013CamelOneAdvanced Stomp• Ack modes• Transactions• Reliable messaging• Protocol Negotiations• Heart-beating23
CamelOne 2013CamelOneStomp and ActiveMQ• Queues and Topics• Reliable Messaging• Temporary destinations• Durable topic subs...
CamelOne 2013CamelOneStomp and ActiveMQ• Message expiration• Composite destinations• Priority consumers• Exclusive consume...
CamelOne 2013CamelOneIn-browser Messaging• Use JavaScript to produce and consumemessages directly from the browser• We nee...
CamelOne 2013CamelOneAjax• Old-school way• Comes bundled with ActiveMQ distribution27
CamelOne 2013CamelOneAjax – explained• Requires additional servlet as an intermediarybetween broker and clients• POST to s...
CamelOne 2013CamelOneAjax – Example29<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><script type="te...
CamelOne 2013CamelOneAjax – Example30amq.sendMessage(”queue://TEST”, “Important Message!”);var myHandler ={rcvMessage: fun...
CamelOne 2013CamelOneWebSocket• Evolution over Ajax and Comet• Defines a “socket” – permanent duplexconnection – between b...
CamelOne 2013CamelOneWebSocket• Fully standardized and part of HTML5 spec• Protocol – standardized by IETF• API – standard...
CamelOne 2013CamelOneWebSocket Example33var connection = new WebSocket("ws://localhost:8161");connection.onopen = function...
CamelOne 2013CamelOneWebSocket + ActiveMQ• WebSocket is a plain socket – like a raw TCP• We need a protocol on top of it t...
CamelOne 2013CamelOneWebSocket + ActiveMQ• New ws and wss transports• wss transport needs SSL context configuration35<tran...
CamelOne 2013CamelOnestomp-websocket• Client side library stomp-websocket• http://github.com/jmesnil/stomp-websocket• Supp...
CamelOne 2013CamelOne stomp-websocketExample37var client = Stomp.client("ws://localhost:61614");var connected = false;clie...
CamelOne 2013CamelOneMessaging for Mobile• Different set of requirements• Low bandwidth network• Small footprint• Low powe...
CamelOne 2013CamelOneMQTT• http://mqtt.org/ - MQ Telemetry Transport• IoT (Internet of Things) protocol• Efficient binary ...
CamelOne 2013CamelOneMQTT Features• Low bandwidth• Smallest frame 2 bytes• Unreliable networks• Small footprint40
CamelOne 2013CamelOneMQTT for mobile• Efficient battery usage - Power Profiliing: MQTTon Android -http://stephendnicholas....
CamelOne 2013CamelOneMQTT• Publish/subscribe protocol – topics only• 3 QoS Options:• At Most Once – message loss might occ...
CamelOne 2013CamelOneMQTT + ActiveMQ• Available transports• NIO implementation for better scalability• SSL for secure comm...
CamelOne 2013CamelOneMQTT client• mqtt-client https://github.com/fusesource/mqtt-client• APIs:• Blocking• Callback• Future44
CamelOne 2013CamelOneMQTT Example45MQTT mqtt = new MQTT();mqtt.setHost("localhost", 1883);final CallbackConnection connect...
CamelOne 2013CamelOneMQTT Example46connection.connect(new Callback<Void>() {public void onSuccess(Void value) {connection....
CamelOne 2013CamelOneMQTT Example47final Promise<Buffer> result = new Promise<Buffer>();connection.listener(new Listener()...
CamelOne 2013CamelOneMQTT Example48connection.connect(new Callback<Void>() {public void onSuccess(Void aVoid) {Topic[] top...
CamelOne 2013CamelOneMQTT Android Example• https://github.com/jsherman1/android-mqtt-demo/49
CamelOne 2013CamelOneStriking the Balance• Lots of possibilities, how to choose right?• Native mobile apps should consider...
CamelOne 2013CamelOneStomp pitfall• Short-lived connections• Every page view, open a new connection to thebroker• Puts hea...
CamelOne 2013CamelOneStomp configuration52<destinationPolicy><policyMap><policyEntries><policyEntry queue=">" producerFlow...
CamelOne 2013CamelOneConclusion• Messaging is not the thing of the enterpriseanymore• Things want to get integrated• We ha...
CamelOne 2013CamelOneAMA• Links• Stomp - http://stomp.github.com• https://github.com/fusesource/stompjms• MQTT – http://mq...
Upcoming SlideShare
Loading in...5
×

Messaging for Web and Mobile with Apache ActiveMQ

5,500

Published on

Published in: Technology
0 Comments
13 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
5,500
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
0
Likes
13
Embeds 0
No embeds

No notes for slide

Messaging for Web and Mobile with Apache ActiveMQ

  1. 1. CamelOne 2013June 10-11 2013Boston, MAMessaging for web andmobile with ApacheActiveMQBy Bosanac Dejan1
  2. 2. CamelOne 2013CamelOne2Bosanac Dejan?• Senior Sofware Engineer at RedHat• Apache ActiveMQ committer and PMC member• Co-author of ActiveMQ in Action• Blog – http://sensatic.net• Twitter – http://twitter.com/dejanb
  3. 3. CamelOne 2013CamelOneAgenda• Challenges of web messaging• REST vs Stomp• In-browser messaging (Ajax vs Web Sockets)• Mobile messaging using MQTT• Striking the balance3
  4. 4. CamelOne 2013CamelOneMessaging for Web• Connect from any web application backend(Ruby, PHP, Python, …)• Connect directly from the browser (AJAX, WebSockets)• The main requirement is simplicity4
  5. 5. CamelOne 2013CamelOneWhat’s wrong with Http?• Nothing at all!• Ideal for simple request-reply communication• Lacks semantics for publish-subscribe andpoint-to-point communication5
  6. 6. CamelOne 2013CamelOneLimitations• Pull based protocol• Easy simple producing• There’s no concept of consumer or subscription• There’s no concept of transactions6
  7. 7. CamelOne 2013CamelOnePull Consuming• HTTP techniques• Long polling• Comet• Maintain a state• Session• ClientID7
  8. 8. CamelOne 2013CamelOnePush Consuming• Web Hooks – http://webhooks.org• Provide a callback (HTTP URL) to be called onevent• Trigger callback on every message8
  9. 9. CamelOne 2013CamelOne Camel HTTPcomponent9<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring”><route><from uri="activemq:topic:events"/><to uri="http://mysite.com/events"/></route></camelContext>• HawtIO – http://hawt.io• Missing API for dynamically managingsubscribers
  10. 10. CamelOne 2013CamelOneStomp – what it is?• http://stomp.github.com• Simple Text Orientated Messaging Protocol• HTTP for the messaging realm10
  11. 11. CamelOne 2013CamelOneStomp – basics• Very simple, so it’s easy to write clients andservers in practically any language• A lot of client APIs in C, Java, Ruby, Pyhton, JS,PHP• Implemented by ActiveMQ, Apollo, HornetQ,RabbitMQ11
  12. 12. CamelOne 2013CamelOneStomp - Protocol• Text based headers,similar to HTTP• Can transport binarybodies• Frame command forevery messagingconcept, likeCONNECT, MESSAGE,SUBSCRIBE, ACK, etc.12MESSAGEsubscription:0message-id:007destination:/queue/acontent-type:text/plainhello queue a^@
  13. 13. CamelOne 2013CamelOneStomp + ActiveMQ• Available transports• NIO implementation for better scalability• SSL for secure communication13<transportConnectors><transportConnector name=”stomp" uri=”stomp://0.0.0.0:61613"/><transportConnector name=”stomp+nio" uri=”stomp+nio://0.0.0.0:61614"/><transportConnector name=”stomp+ssl" uri=”stomp+ssl://0.0.0.0:61615"/><transportConnector name=”stomp+nio+ssl"uri=”stomp+nio+ssl://0.0.0.0:61615"/></transportConnectors>
  14. 14. CamelOne 2013CamelOneStomp Java Client• StompJMS -https://github.com/fusesource/stompjms• APIs:• JMS• Blocking• Future• Callback14
  15. 15. CamelOne 2013CamelOne15Stomp stomp = new Stomp("localhost", 61613);Future<FutureConnection> future = stomp.connectFuture();FutureConnection connection = future.await();CONNECThost:localhostaccept-version:1.1CONNECTEDheart-beat:0,0session:ID:vidra.local-56933-1369046267671-2:1server:ActiveMQ/5.9-SNAPSHOTversion:1.1
  16. 16. CamelOne 2013CamelOne16StompFrame frame = new StompFrame(SEND);frame.addHeader(DESTINATION, StompFrame.encodeHeader("/queue/test"));frame.addHeader(MESSAGE_ID, StompFrame.encodeHeader("test"));frame.content(new Buffer("Important Message".getBytes("UTF-8")));Future<Void> sendFuture = connection.send(frame);sendFuture.await();SENDmessage-id:testdestination:/queue/testcontent-length:17Important Message
  17. 17. CamelOne 2013CamelOne17StompFrame disconnect = new StompFrame(DISCONNECT);Future<Void> disconnectFuture = connection.send(disconnect);disconnectFuture.await();DISCONNECT
  18. 18. CamelOne 2013CamelOne18Stomp stomp = new Stomp("localhost", 61613);Future<FutureConnection> future = stomp.connectFuture();FutureConnection connection = future.await();CONNECThost:localhostaccept-version:1.1CONNECTEDheart-beat:0,0session:ID:vidra.local-56933-1369046267671-2:1server:ActiveMQ/5.9-SNAPSHOTversion:1.1
  19. 19. CamelOne 2013CamelOne19Future<StompFrame> receiveFuture = connection.receive();StompFrame frame = new StompFrame(SUBSCRIBE);frame.addHeader(DESTINATION, StompFrame.encodeHeader("/queue/test"));AsciiBuffer id = connection.nextId();frame.addHeader(ID, id);Future<StompFrame> response = connection.request(frame);response.await();SUBSCRIBEreceipt:2destination:/queue/testid:1RECEIPTreceipt-id:2
  20. 20. CamelOne 2013CamelOne20StompFrame received = receiveFuture.await();System.out.println(received.content());MESSAGEmessage-id:ID:vidra.local-56933-1369046267671-2:1:-1:1:1destination:/queue/testtimestamp:1369046474700expires:0subscription:1content-length:17priority:4Important Message
  21. 21. CamelOne 2013CamelOne21StompFrame unsubscribe = new StompFrame(UNSUBSCRIBE);unsubscribe.addHeader(ID, id);Future<Void> unsubscribeFuture = connection.send(unsubscribe);unsubscribeFuture.await();UNSUBSCRIBEid:1
  22. 22. CamelOne 2013CamelOne22StompFrame disconnect = new StompFrame(DISCONNECT);Future<Void> disconnectFuture = connection.send(disconnect);disconnectFuture.await();DISCONNECT
  23. 23. CamelOne 2013CamelOneAdvanced Stomp• Ack modes• Transactions• Reliable messaging• Protocol Negotiations• Heart-beating23
  24. 24. CamelOne 2013CamelOneStomp and ActiveMQ• Queues and Topics• Reliable Messaging• Temporary destinations• Durable topic subscribers• Destination wildcards• Message selectors24
  25. 25. CamelOne 2013CamelOneStomp and ActiveMQ• Message expiration• Composite destinations• Priority consumers• Exclusive consumers25
  26. 26. CamelOne 2013CamelOneIn-browser Messaging• Use JavaScript to produce and consumemessages directly from the browser• We need to leverage existing web technologieslike Ajax and Web Sockets• We need a web server that’s able tocommunicate with the broker26
  27. 27. CamelOne 2013CamelOneAjax• Old-school way• Comes bundled with ActiveMQ distribution27
  28. 28. CamelOne 2013CamelOneAjax – explained• Requires additional servlet as an intermediarybetween broker and clients• POST to send messages• Jetty continuations to receive messages28
  29. 29. CamelOne 2013CamelOneAjax – Example29<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><script type="text/javascript" src="js/amq_jquery_adapter.js"></script><script type="text/javascript" src="js/amq.js"></script><script type="text/javascript">var amq = org.activemq.Amq;amq.init({uri: amq,logging: true,timeout: 20});</script>
  30. 30. CamelOne 2013CamelOneAjax – Example30amq.sendMessage(”queue://TEST”, “Important Message!”);var myHandler ={rcvMessage: function(message){console.log(“Received message: ” + message);}};amq.addListener(“myListener”, “queue://TEST”, myHandler.rcvMessage);
  31. 31. CamelOne 2013CamelOneWebSocket• Evolution over Ajax and Comet• Defines a “socket” – permanent duplexconnection – between browser and server• Server and browser can exchange messages31
  32. 32. CamelOne 2013CamelOneWebSocket• Fully standardized and part of HTML5 spec• Protocol – standardized by IETF• API – standardized by W3C• Supported by most modern web servers andbrowsers32
  33. 33. CamelOne 2013CamelOneWebSocket Example33var connection = new WebSocket("ws://localhost:8161");connection.onopen = function() {console.log("Connection opened!");};connection.onmessage = function(msg) {console.log("Received Message: " + msg.data);};connection.onerror = function(error) {console.log("Error occured: " + error);}connection.onclose = function(evt) {console.log("Connection closed!");};connection.send("Important Message!");connection.close();
  34. 34. CamelOne 2013CamelOneWebSocket + ActiveMQ• WebSocket is a plain socket – like a raw TCP• We need a protocol on top of it to use allconcepts of messaging and connect to broker• WebSocket+Stomp ideal combination!34
  35. 35. CamelOne 2013CamelOneWebSocket + ActiveMQ• New ws and wss transports• wss transport needs SSL context configuration35<transportConnectors><transportConnector name="websocket" uri="ws://0.0.0.0:61613"/><transportConnector name="secure_websocket" uri="wss://0.0.0.0:61614"/></transportConnectors>
  36. 36. CamelOne 2013CamelOnestomp-websocket• Client side library stomp-websocket• http://github.com/jmesnil/stomp-websocket• Supports Stomp 1.1• Not a “pure” Stomp as it requires WebSockethandshake36
  37. 37. CamelOne 2013CamelOne stomp-websocketExample37var client = Stomp.client("ws://localhost:61614");var connected = false;client.connect("admin", "admin", function() {connected = true;client.subscribe("/queue/test", function(message) {console.log("Received message " + message);}});if (connected) {client.send("/queue/test", {priority: 9}, "Important Message!");}if (connected) {client.disconnect();}
  38. 38. CamelOne 2013CamelOneMessaging for Mobile• Different set of requirements• Low bandwidth network• Small footprint• Low power usage38
  39. 39. CamelOne 2013CamelOneMQTT• http://mqtt.org/ - MQ Telemetry Transport• IoT (Internet of Things) protocol• Efficient binary protocol• Developed by IBM for embedded devicestelemetry39
  40. 40. CamelOne 2013CamelOneMQTT Features• Low bandwidth• Smallest frame 2 bytes• Unreliable networks• Small footprint40
  41. 41. CamelOne 2013CamelOneMQTT for mobile• Efficient battery usage - Power Profiliing: MQTTon Android -http://stephendnicholas.com/archives/219• Ideal for native mobile applications• Usecase: Facebook messanger• Phone-to-phone delivery in milliseconds, rather thanseconds• Without killing battery life41
  42. 42. CamelOne 2013CamelOneMQTT• Publish/subscribe protocol – topics only• 3 QoS Options:• At Most Once – message loss might occur• At Least Once – duplicates might occur• Exactly Once – guaranteed delivery42
  43. 43. CamelOne 2013CamelOneMQTT + ActiveMQ• Available transports• NIO implementation for better scalability• SSL for secure communication43<transportConnectors><transportConnector name=”mqtt" uri=”mqtt://0.0.0.0:1883"/><transportConnector name=”mqtt+nio" uri=”mqtt+nio://0.0.0.0:1884"/><transportConnector name=”mqtt+ssl" uri=”mqtt+ssl://0.0.0.0:1885"/><transportConnector name=”mqtt+nio+ssl"uri=”mqtt+nio+ssl://0.0.0.0:1886"/></transportConnectors>
  44. 44. CamelOne 2013CamelOneMQTT client• mqtt-client https://github.com/fusesource/mqtt-client• APIs:• Blocking• Callback• Future44
  45. 45. CamelOne 2013CamelOneMQTT Example45MQTT mqtt = new MQTT();mqtt.setHost("localhost", 1883);final CallbackConnection connection = mqtt.callbackConnection();
  46. 46. CamelOne 2013CamelOneMQTT Example46connection.connect(new Callback<Void>() {public void onSuccess(Void value) {connection.publish("test","Important Message!".getBytes(),QoS.AT_LEAST_ONCE,false,null);}public void onFailure(Throwable value) {connection.disconnect(null);}});
  47. 47. CamelOne 2013CamelOneMQTT Example47final Promise<Buffer> result = new Promise<Buffer>();connection.listener(new Listener() {public void onConnected() {}public void onDisconnected() {}public void onPublish(UTF8Buffer topic, Buffer body,Runnable ack) {result.onSuccess(body);ack.run();}public void onFailure(Throwable value) {result.onFailure(value);connection.disconnect(null);}});LOG.info("Received: " + result.await(5, TimeUnit.MINUTES));
  48. 48. CamelOne 2013CamelOneMQTT Example48connection.connect(new Callback<Void>() {public void onSuccess(Void aVoid) {Topic[] topics = {new Topic(utf8("test"), QoS.AT_LEAST_ONCE)};connection.subscribe(topics, null);}public void onFailure(Throwable value) {connection.disconnect(null);}});
  49. 49. CamelOne 2013CamelOneMQTT Android Example• https://github.com/jsherman1/android-mqtt-demo/49
  50. 50. CamelOne 2013CamelOneStriking the Balance• Lots of possibilities, how to choose right?• Native mobile apps should consider MQTT• Do you need live updates in your browser?• WebSockets ideal for HTML5 apps with limitednumber of users that needs instant update• For everyone else, theres backend messaging50
  51. 51. CamelOne 2013CamelOneStomp pitfall• Short-lived connections• Every page view, open a new connection to thebroker• Puts heavy load on the broker• Eliminates all advance messaging mechanisms– message prefetches, producer flow control,etc.51
  52. 52. CamelOne 2013CamelOneStomp configuration52<destinationPolicy><policyMap><policyEntries><policyEntry queue=">" producerFlowControl="false"></policyEntry></policyEntries></policyMap></destinationPolicy><transportConnectors><transportConnector name="stomp+nio"uri="stomp+nio://0.0.0.0:61613?transport.closeAsync=false"/></transportConnectors>
  53. 53. CamelOne 2013CamelOneConclusion• Messaging is not the thing of the enterpriseanymore• Things want to get integrated• We have technology to do that TODAY!53
  54. 54. CamelOne 2013CamelOneAMA• Links• Stomp - http://stomp.github.com• https://github.com/fusesource/stompjms• MQTT – http://mqtt.org• https://github.com/fusesource/mqtt-client• Blog: http://sensatic.net• Twitter: http://twitter.com/dejanb54

×