Ajax JQuery + SpringBoot RestAPI + ActiveMQ Producer/Consumer example

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:

JQuery-SpringBoot-RestAPI-ActiveMQ-Producer-Consumer + project-structure

JQuery-SpringBoot-RestAPI-ActiveMQ-Producer-Consumer + producer-consumer

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:

JQuery-SpringBoot-RestAPI-ActiveMQ-Producer-Consumer + results

ActiveMQ state:

JQuery-SpringBoot-RestAPI-ActiveMQ-Producer-Consumer + 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 List tasks = 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 List getAll(){
		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!
" + "---> Task's Info: id = " + result.id + ", name = " + result.name + "

"); console.log(result); }, error : function(e) { alert("Error!") console.log("ERROR: ", e); } }); // Reset FormData after Posting resetData(); } function resetData(){ $("#id").val(""); $("#name").val(""); } })

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("
  • " + task + "
  • "); }); console.log("Success: ", result); }, error : function(e) { $("#getResultDiv").html("Error"); console.log("ERROR: ", e); } }); } })

    SourceCode

    SpringBootActiveMQ

    15 thoughts on “Ajax JQuery + SpringBoot RestAPI + ActiveMQ Producer/Consumer example”

    1. Youre so cool! I dont suppose Ive read anything such as this before. So nice to discover somebody by original applying for grants this subject. realy thanks for beginning this up. this website is one thing that is required on-line, a person after a little originality. helpful problem for bringing new things for the world wide web!

    2. When I originally commented I clicked the -Notify me when new surveys are added- checkbox now whenever a comment is added I buy four emails with similar comment. Is there by any means you possibly can remove me from that service? Thanks!

    3. Hi there. Very nice blog!! Man .. Excellent .. Amazing .. I’ll bookmark your website and take the feeds additionally…I am glad to locate numerous useful info right here within the post. Thanks for sharing…

    4. Woah! I’m really digging the template/theme of this website. It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between user friendliness and appearance. I must say that you’ve done a great job with this. Additionally, the blog loads extremely fast for me on Internet explorer. Outstanding Blog!

    Leave a Reply

    Your email address will not be published. Required fields are marked *