Angular 8 + ActiveMQ Producer/Consumer + SpringBoot RestAPIs example

In the tutorial, we show how to Producer/Consumer data from ActiveMQ with Angular 8 & SpringBoot RestAPIs.

Related posts:
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

Related Pages:

Technologies

  • Java 1.8
  • Maven 3.3.9
  • Spring Tool Suite – Version 3.9.4.RELEASE
  • Spring Boot: 2.0.3.RELEASE
  • ActiveMQ
  • Angular 8

Overview

We create a Spring JMS ActiveMQ with JMS Producer & JMS Consumer as below:

Angular-6-Spring-Boot-RestAPI-ActiveMQ-Producer-Consumer +springboot-project-structure

Angular-6-Spring-Boot-RestAPI-ActiveMQ-Producer-Consumer + activemq-producer-consumer

Then expose RestAPIs to POST/GET data to/from ActiveMQ:

  • @PostMapping(value="/api/task")
  • @GetMapping(value="/api/tasks")

Use Angular Client to submit/get data from ActiveMQ via above RestAPI:

Angular-6-Spring-Boot-RestAPI-ActiveMQ-Producer-Consumer +add-new-task

Angular-6-Spring-Boot-RestAPI-ActiveMQ-Producer-Consumer +processing-all-task

ActiveMQ state:

Angular-6-Spring-Boot-RestAPI-ActiveMQ-Producer-Consumer + activemq-state

Practice

SpringBoot Backend

Setup SpringBoot project

Use SpringToolSuite to create a SpringBoot project with below dependencies:

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-jms</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.activemq</groupId>
	<artifactId>activemq-broker</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

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.CrossOrigin;
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;

@CrossOrigin(origins = "http://localhost:4200")
@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;
	}
}

Angular Frontend

Setup Angular Project

Setup guide:

  • Create Angular project with commandline: ng new angular6-client
  • Generate Task model with commandline ng generate class Task
  • Generate TaskService with commandline ng generate service Task
  • Generate TaskComponent with commandline ng generate component Task

Then install Bootstrap by commandline ->

>npm install bootstrap jquery --save

Configure installed Bootstrap & JQuery in angular.json file ->


...
 
"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
  "node_modules/jquery/dist/jquery.min.js",
  "node_modules/bootstrap/dist/js/bootstrap.min.js"
]
 
...

Data Model

Task ->


export class Task {
    id: number;
    name: string;
}

Implement HttpClient Service

TaskService ->


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Task } from './task';
 
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
 
@Injectable({
  providedIn: 'root'
})
export class   {
  constructor( 
    private http: HttpClient
  ) { }
 
  getTasks (): Observable {
    return this.http.get("http://localhost:8080/api/tasks")
  }
  
  addTask (task: Task): Observable {
    return this.http.post("http://localhost:8080/api/task", task, httpOptions);
  }
}

Implement ActiveMQ Component

activemq-task.component.html ->

<div [hidden]="submitted">
    <h3>Add Task</h3>
    <form #addTaskForm="ngForm">

      <div class="form-group">
        <label for="id">Id</label>
        <input type="number" class="form-control" id="id" 
        placeholder="Enter Id"
        required
        [(ngModel)]="task.id" name="id" #id="ngModel">
        <div [hidden]="id.valid || id.pristine"
              class="alert alert-danger">
            Id is required
        </div>
      </div>
 
      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name" placeholder="Enter Task Name" 
        required
        [(ngModel)]="task.name" name="name" #name="ngModel">
        <div [hidden]="name.valid || name.pristine"
             class="alert alert-danger">
            Name is required
        </div>
      </div>  
      <button class="btn btn-dark" (click)="addTask()" [disabled]="!addTaskForm.form.valid">Add Task</button>
    </form>
</div>
 
<div [hidden]="!submitted">
  <p>Submitted Successfully! -> <span class="badge badge-dark">Task's Info -> Id: {{task.id}}, Name: {{task.name}}</span></p>
	<div class="btn-group btn-group-sm">
    <button class="btn btn-secondary" (click)="newTask(); addTaskForm.reset();">New Task</button>
    <button class="btn btn-secondary" (click)="processTasks();">Process Tasks</button>
  </div>
  <div [hidden]="!processing">
      <br>
      <h5>Processing</h5>
      <ul>
        <li *ngFor="let task of tasks">
          Task id = {{task.id}}, name = {{task.name}}
        </li>
      </ul>
  </div>
</div>

activemq-task.component.ts ->


import { Component, OnInit } from '@angular/core';
import { Task } from '../task';
import { TaskService } from '../task.service';

@Component({
  selector: 'app-activemq-task',
  templateUrl: './activemq-task.component.html',
  styleUrls: ['./activemq-task.component.css']
})
export class ActivemqTaskComponent{

  task = new Task();
  tasks: Task[];
  submitted = false;
  processing = false;

  constructor(private taskService: TaskService) { }

  newTask(): void {
    this.submitted = false;
    this.processing = false;
    this.task = new Task();
  }
 
  addTask() {
    this.submitted = true;
    this.taskService.addTask(this.task)
    .subscribe();
  }

  processTasks(){
    this.processing = true;
    return this.taskService.getTasks()
                .subscribe(
                  tasks => {
                    console.log(tasks);
                    this.tasks = tasks;
                  }
                );
  }
}

– Create style file assets/forms.css ->


.ng-valid[required], .ng-valid.required  {
    border-left: 5px solid rgba(32, 77, 32, 0.623);
}
 
.ng-invalid:not(form)  {
    border-left: 5px solid rgb(148, 27, 27);
}

– Add above style file assets/forms.css to index.html file ->

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular6Client</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="assets/forms.css">
</head>
<body>
  <app-root></app-root>
</body>
</html>

– Add app-activemq-task selector to app.component.html file ->

<div class="container">
  <div class="row">
    <div class="col-sm-4"> 
      <app-activemq-task></app-activemq-task>
   </div>
  </div>
</div>

Run & Check Results

– Build & Run SpringBoot project with commandlines {mvn clean install, mvn spring-boot:run}.
– Run the Angular project as commandline: ng serve

Add Task ->

Angular-6-Spring-Boot-RestAPI-ActiveMQ-Producer-Consumer +add-new-task

Angular-6-Spring-Boot-RestAPI-ActiveMQ-Producer-Consumer +submit-successfully

Get Tasks ->

Angular-6-Spring-Boot-RestAPI-ActiveMQ-Producer-Consumer +processing-all-task

ActiveMQ state ->

Angular-6-Spring-Boot-RestAPI-ActiveMQ-Producer-Consumer + activemq-state

SourceCode

SpringBootRestAPIsActiveMQ
Angular6-Client

46 thoughts on “Angular 8 + ActiveMQ Producer/Consumer + SpringBoot RestAPIs example”

  1. Hey! This is my first visit to your blog! We are a collection of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job!

  2. Terrific work! This is the type of info that should be shared around the web. Shame on Google for not positioning this post higher! Come on over and visit my website . Thanks =)

  3. Thanks so much for giving everyone an extraordinarily spectacular chance to read articles and blog posts from this website. It is often so lovely and jam-packed with a good time for me personally and my office mates to visit your blog nearly 3 times in 7 days to see the newest guides you have got. Not to mention, I’m also at all times astounded concerning the amazing strategies you give. Selected 2 areas on this page are in reality the best I’ve had.

  4. 2542 178357I discovered your weblog website on google and check just a couple of of your early posts. Proceed to preserve up the outstanding operate. I just extra up your RSS feed to my MSN Details Reader. Seeking forward to reading far more from you in a although! 600697

  5. The the very next time I read a blog, I hope who’s doesnt disappoint me up to this. I mean, I know it was my solution to read, but I actually thought youd have something fascinating to express. All I hear can be a lot of whining about something that you could fix should you werent too busy interested in attention.

  6. The post is definitely nicely written but it contains many useful facts. I am just ready to find your distinguished way of writing the post. So now you make it easy for me to learn and implement. Nice one for sharing around.

  7. I as well as my friends have been reading through the best solutions located on your website and then at once developed an awful feeling I never thanked you for those tips. The men came so very interested to read them and have now unquestionably been having fun with those things. I appreciate you for actually being very helpful and then for obtaining variety of ideal themes millions of individuals are really wanting to discover. Our honest apologies for not saying thanks to you earlier.

  8. Strange this put up is totaly unrelated to what I used to be searching google for, but it surely was indexed at the first page. I guess your doing one thing right if Google likes you sufficient to put you at the first web page of a non similar search.

  9. An fascinating discussion will be worth comment. I’m sure that you need to write much more about this topic, may possibly not certainly be a taboo subject but usually people are not enough to communicate in on such topics. To another location. Cheers

  10. 978179 442689I havent checked in here for some time as I thought it was acquiring boring, but the last couple of posts are wonderful quality so I guess Ill add you back to my everyday bloglist. You deserve it my friend 448622

  11. 26881 784188Have read a couple of of the articles on your website now, and I genuinely like your style of blogging. I added it to my favorites blog site list and will probably be checking back soon. 334432

  12. Magnificent items from you, man. I’ve keep in mind your stuff previous to and you’re just too great.
    I really like what you have received right
    here, certainly like what you are stating and
    the way through which you are saying it. You’re making it entertaining and you still care for to keep it smart.

    I can’t wait to learn much more from you. This is really a
    tremendous website.

  13. Hi! I know this is kinda off topic however I’d figured I’d ask.

    Would you be interested in trading links or maybe guest writing
    a blog article or vice-versa? My website goes over a lot of the same topics as yours and
    I feel we could greatly benefit from each other. If you might be interested feel free to send me an email.

    I look forward to hearing from you! Fantastic blog
    by the way!

  14. Great post. I was checking constantly this blog and I’m impressed!
    Very useful information particularly the last
    part 🙂 I care for such information a lot.
    I was looking for this particular information for a
    long time. Thank you and best of luck.

  15. My partner and I stumbled over here coming from a different web page and thought I should check things out.
    I like what I see so i am just following you. Look forward to
    looking over your web page again.

  16. Hi, i think that i saw you visited my weblog so i came to “return the favor”.I’m attempting to find things to enhance my website!I suppose its
    ok to use some of your ideas!!

  17. Can I simply say what a comfort to find someone who genuinely understands what they’re discussing on the net.

    You definitely realize how to bring a problem to
    light and make it important. A lot more people need to look at
    this and understand this side of your story. It’s surprising you are not more popular because you surely have the gift.

  18. Undeniably believe that that you stated. Your favourite reason appeared
    to be on the net the simplest factor to bear in mind of.
    I say to you, I certainly get annoyed whilst other people think about issues that they plainly don’t know about.
    You controlled to hit the nail upon the top and outlined out
    the entire thing with no need side effect , other people
    could take a signal. Will likely be again to get more.

    Thank you

  19. Just desire to say your article is as astounding. The
    clarity in your post is simply spectacular and i could assume
    you are an expert on this subject. Well with your permission allow me
    to grab your feed to keep updated with forthcoming post.
    Thanks a million and please carry on the enjoyable
    work.

  20. Hello, i believe that i noticed you visited my web site
    thus i got here to go back the want?.I am attempting
    to find issues to improve my website!I guess its good enough to
    use a few of your ideas!!

  21. First off I would like to say wonderful blog!

    I had a quick question in which I’d like to ask if you don’t mind.
    I was curious to find out how you center yourself and clear your head before writing.
    I’ve had trouble clearing my thoughts in getting
    my thoughts out there. I truly do take pleasure in writing however it just seems like the first 10
    to 15 minutes are usually lost just trying to figure out how to begin. Any suggestions or hints?
    Thanks!

  22. Fantastic site you have here but I was curious if you knew of any user discussion forums that cover the same topics talked about in this article?
    I’d really love to be a part of community where I can get suggestions from other experienced
    individuals that share the same interest. If you have
    any suggestions, please let me know. Many thanks!

  23. Wonderful website you have here but I was wanting to
    know if you knew of any discussion boards that cover the same topics talked
    about here? I’d really love to be a part of group where I can get feedback from other experienced individuals that share the same interest.

    If you have any recommendations, please let me know.
    Bless you!

  24. Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot
    of spam responses? If so how do you prevent it,
    any plugin or anything you can suggest? I get so much
    lately it’s driving me mad so any help is very much appreciated.

  25. Hey there! I realize this is sort of off-topic but I had
    to ask. Does managing a well-established website such as yours require a
    lot of work? I’m brand new to running a blog however I do write in my journal every day.
    I’d like to start a blog so I can easily share my experience and views online.
    Please let me know if you have any recommendations or tips for brand
    new aspiring blog owners. Appreciate it!

  26. This is very interesting, You’re a very professional blogger.
    I’ve joined your rss feed and look ahead to searching for more of your wonderful post.
    Also, I’ve shared your website in my social networks

  27. Fascinating blog! Is your theme custom made or did you
    download it from somewhere? A design like yours with a
    few simple adjustements would really make my blog stand
    out. Please let me know where you got your design. Appreciate it

  28. You can definitely see your expertise within the article you write.
    The sector hopes for more passionate writers such as you who are not afraid to mention how they
    believe. All the time go after your heart.

  29. We absolutely love your blog and find the majority
    of your post’s to be just what I’m looking for.

    Does one offer guest writers to write content for you? I wouldn’t mind producing a post or elaborating on some of the subjects you write regarding here.

    Again, awesome website!

  30. Hey there would you mind letting me know which webhost you’re working with?
    I’ve loaded your blog in 3 completely different
    browsers and I must say this blog loads a lot faster then most.
    Can you suggest a good hosting provider at a honest price?
    Kudos, I appreciate it!

  31. Great items from you, man. I’ve understand your stuff prior
    to and you are simply extremely magnificent. I actually like what you’ve acquired
    right here, certainly like what you’re stating and the best way by which you assert it.
    You’re making it enjoyable and you still take care of to keep it
    sensible. I can’t wait to learn much more from you. This is
    really a terrific website.

Leave a Reply

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