In the tutorial, we show how to Producer/Consumer data from ActiveMQ with JQuery & SpringBoot RestAPIs.
Related posts:
– How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot
– ActiveMQ Producer/Consumer + SpringBoot RestAPIs example
– RabbitMq – How to create Spring RabbitMq Publish/Subcribe pattern with SpringBoot
– How to use Spring Kafka JsonSerializer (JsonDeserializer) to produce/consume Java Object messages
Technologies
- Java 1.8
- Maven 3.3.9
- Spring Tool Suite – Version 3.9.4.RELEASE
- Spring Boot: 2.0.3.RELEASE
- ActiveMQ
- JQuery
Overview
We create a Spring JMS ActiveMQ with JMS Producer & JMS Consumer as below:
Then expose RestAPIs to POST/GET data to/from ActiveMQ:
@PostMapping(value="/api/task")
@GetMapping(value="/api/tasks")
Use JQuery Client to submit/get data from ActiveMQ via above RestAPI:
ActiveMQ state:
Practice
Backend
Setup SpringBoot project
Use SpringToolSuite to create a SpringBoot project with below dependencies:
org.springframework.boot spring-boot-starter-thymeleaf org.springframework spring-jms org.apache.activemq activemq-broker org.springframework.boot spring-boot-starter-web
ActiveMQ Connection Factory
ActiveMqConnectionFactoryConfig
->
package com.ozenero.activemq.config; import javax.jms.ConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.config.DefaultJmsListenerContainerFactory; import org.springframework.jms.config.JmsListenerContainerFactory; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.support.converter.MappingJackson2MessageConverter; import org.springframework.jms.support.converter.MessageConverter; import org.springframework.jms.support.converter.MessageType; @Configuration public class ActiveMqConnectionFactoryConfig { @Value("${gkz.activemq.broker.url}") String brokerUrl; @Value("${gkz.activemq.borker.username}") String userName; @Value("${gkz.activemq.borker.password}") String password; /* * Initial ConnectionFactory */ @Bean public ConnectionFactory connectionFactory(){ ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); connectionFactory.setBrokerURL(brokerUrl); connectionFactory.setUserName(userName); connectionFactory.setPassword(password); return connectionFactory; } @Bean // Serialize message content to json using TextMessage public MessageConverter jacksonJmsMessageConverter() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); converter.setTargetType(MessageType.TEXT); converter.setTypeIdPropertyName("_type"); return converter; } /* * Used for Receiving Message */ @Bean public JmsListenerContainerFactory> jsaFactory(ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer configurer) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setMessageConverter(jacksonJmsMessageConverter()); configurer.configure(factory, connectionFactory); return factory; } /* * Used for Sending Messages. */ @Bean public JmsTemplate jmsTemplate(){ JmsTemplate template = new JmsTemplate(); template.setMessageConverter(jacksonJmsMessageConverter()); template.setConnectionFactory(connectionFactory()); return template; } }
Add ActiveMQ configuration in application.properties
->
gkz.activemq.broker.url=tcp://localhost:61616 gkz.activemq.borker.username=admin gkz.activemq.borker.password=admin gkz.activemq.queue=gkz-queue
Data Model
– Create Task model ->
package com.ozenero.activemq.model; public class Task { private Long id; private String name; public Task(){ } public Task(Long id, String name){ this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
– Create MessageStorage
to storage Task
list ->
package com.ozenero.activemq.model; import java.util.ArrayList; import java.util.List; public class MessageStorage { private Listtasks = new ArrayList (); public void add(Task task) { tasks.add(task); } public void clear() { tasks.clear(); } public List getAll(){ return tasks; } }
Create a bean for MessageStorage
->
package com.ozenero.activemq.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.ozenero.activemq.model.MessageStorage; @Configuration public class BeanConfiguration { @Bean public MessageStorage customerStorage() { return new MessageStorage(); } }
JMS Producer
JmsProducer
send messages to ActiveMQ ->
package com.ozenero.activemq.jms.producer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Component; import com.ozenero.activemq.model.Task; @Component public class JmsProducer { @Autowired JmsTemplate jmsTemplate; @Value("${gkz.activemq.queue}") String queue; public void send(Task task){ jmsTemplate.convertAndSend(queue, task); } }
JMS Consumer
JmsConsumer
recieves messages from ActiveMQ ->
package com.ozenero.activemq.jms.consumer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; import com.ozenero.activemq.model.MessageStorage; import com.ozenero.activemq.model.Task; @Component public class JmsConsumer { @Autowired private MessageStorage taskStorage; @JmsListener(destination = "${gkz.activemq.queue}", containerFactory="jsaFactory") public void receive(Task task){ taskStorage.add(task); } }
Rest APIs
RestAPI
->
package com.ozenero.activemq.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.ozenero.activemq.jms.producer.JmsProducer; import com.ozenero.activemq.model.MessageStorage; import com.ozenero.activemq.model.Task; @RestController public class RestAPIs { @Autowired JmsProducer jmsProducer; @Autowired private MessageStorage taskStorage; @PostMapping(value="/api/task") public Task postCustomer(@RequestBody Task task){ jmsProducer.send(task); return task; } @GetMapping(value="/api/tasks") public ListgetAll(){ List tasks = new ArrayList (taskStorage.getAll()); taskStorage.clear(); return tasks; } }
Frontend
Index.html
/src/main/resources/templates/index.html
->
JQuery + SpringBoot + ActiveMQ Example Task Form
Post/Get Ajax JQuery
resources/static/js/postrequest.js
->
$( document ).ready(function() { // SUBMIT FORM $("#taskForm").submit(function(event) { // Prevent the form from submitting via the browser. event.preventDefault(); ajaxPost(); }); function ajaxPost(){ // PREPARE FORM DATA var formData = { id : $("#id").val(), name : $("#name").val() } // DO POST $.ajax({ type : "POST", contentType : "application/json", url : window.location + "api/task", data : JSON.stringify(formData), dataType : 'json', success : function(result) { $("#postResultDiv").html("" + "Post Successfully!
"); console.log(result); }, error : function(e) { alert("Error!") console.log("ERROR: ", e); } }); // Reset FormData after Posting resetData(); } function resetData(){ $("#id").val(""); $("#name").val(""); } })
" + "---> Task's Info: id = " + result.id + ", name = " + result.name + "
resources/static/js/getrequest.js
->
$( document ).ready(function() { // GET REQUEST $("#getAllTasks").click(function(event){ event.preventDefault(); ajaxGet(); }); // DO GET function ajaxGet(){ $.ajax({ type : "GET", url : window.location + "api/tasks", success: function(result){ $('#getResultDiv ul').empty(); $.each(result, function(i, task){ var task = "Task -> id = " + task.id + ", name = " + task.name + "
"; $('#getResultDiv ul').append("