Spring Boot + ActiveMQ

We will use Spring boot with ActiveMQ as below –

Github Link:  Download

We can connect to in memory or message queue hosted on external server –

Tools used for below project –

  1. Spring Boot 2.0.3.RELEASE
  2. Spring 5.0.7.RELEASE
  3. ActiveMQ Embeded 8
  4. Maven 3.3
  5. Java 8
  6. Spring Tool Suite IDE (STS)

Step 1: Project Structure

 

 

 

 

 

 

 

 

 

 

Step 2: Create a project named SpringBootMessageQueue in STS (Refer Create new project in STS). Additionally select JMS(ActiveMQ) dependency from starter project  dependencies popup –

Step 3: Below pom.xml will be generated for you by STS .

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.anup.springboot</groupId>
<artifactId>Springboot_HelloWorld</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Springboot_HelloWorld Maven Webapp</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>

<finalName>Springboot_HelloWorld</finalName>
</build>
</project>

The spring-boot-starter-parent provides you all maven defaults required for any spring project.

Since we are developing a spring boot application , we also need to add spring-boot-starter-web dependency. Additionally we need to include spring-boot-starter-activemq for connecting to ActiveMQ.
Let’s do ActiveMQ configuration first.

Application Properties- 

Step 4: Update“Application.properties” file under /src/main/resources folder to create in memory MQ –

spring.activemq.in-memory=true
spring.activemq.pool.enabled=false

If you want to use activemq hosted on external server then you need to do configuration as below –

<span class="crayon-v">spring</span><span class="crayon-sy">.</span><span class="crayon-v">activemq</span><span class="crayon-sy">.</span><span class="crayon-v">broker</span><span class="crayon-o">-</span><span class="crayon-v">url</span><span class="crayon-o">=</span><span class="crayon-v">tcp</span><span class="crayon-o">:</span><span class="crayon-c">//localhost:61616</span>

Spring boot main file

Step 5:  “SpringBootApplicatioMain.java”  file must be created under com.myjavablog package by  STS

package com.anup.springboot;

import javax.jms.Queue;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;

@SpringBootApplication
@EnableJms
public class SpringBootApplicatioMain {

public static void main(String[] args) {
SpringApplication.run(SpringBootApplicatioMain.class, args);
}

@Bean
public Queue queue() {
return new ActiveMQQueue("com.anup.testqueue");
}
}

This is the main file which bootstraps spring application.

We have just added @SpringBootApplication and it does all the work.
Let’s understand more about this annotation.
@SpringBootApplication is an annotation that adds all of the following:

@Configuration – It makes the class as a source of bean definitions for the application context.
@EnableAutoConfiguration – It enables Spring boot to add beans presents in classpath setting and various property setting.
Normally you would add @EnableWebMvc for a Spring MVC application, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath.
This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
@ComponentScan – It tells Spring to look for other components, configurations, and services in the default package, allowing it to find the controllers.

@EnableJMS annotation is used to trigger search for method annotated with @JMSListener, hence to create JMS listener in the background.
If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

 

Step 6: Create a file named “WebSecurityConfiguaration.java” in package com.myjavablog

/**
*
*/
package com.myjavablog;

/**
* @author anupb
*
*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguaration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests().antMatchers("/hello*").access("hasRole('ROLE_ADMIN')").and().formLogin();

}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance()).
withUser("myjavablog").password("secure").roles("ADMIN");
}
}

@EnableWebSecurity – Enables security for our application.

http.authorizeRequests().antMatchers(“/hello*”) – Secures all the URLs containing hello word in it.

http.authorizeRequests().antMatchers(“/hello*”).access(“hasRole(‘ROLE_ADMIN’)”).and().formLogin() – Allows role based access to these URLs . User with only admin can access this URL.

auth.inMemoryAuthentication().withUser(“myjavablog”).password(“secure”).roles(“ADMIN”) – We are using in Memory authentication to authenticate the user. User credentials are stored in memory for this example. We can store them either in database , LDAP etc.

When user provides myjavablog/secure credentials in login form then only he can access URLs with /hello  as this user has ADMIN role.

 

Run the application

Step 10: Right Click on Project -> Debug As -> Maven Build

 

Step 8: Provide goals as below – 

mvn clean install spring-boot:run (Cmd prompt)

Or

 

Step 9:  Now once you run the application, spring boot will create a Queue in a memory and puts the messages onto that queue as below –

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.3.RELEASE)

2018-06-24 21:14:27.007 INFO 17356 --- [ main] c.a.springboot.SpringBootApplicatioMain : Starting SpringBootApplicatioMain on DESKTOP-IK4A0TS with PID 17356 (started by anupb in E:\Study Material\Software Setups\UI\STS_Wksp\SpringBootMessageQueue)
2018-06-24 21:14:27.034 INFO 17356 --- [ main] c.a.springboot.SpringBootApplicatioMain : No active profile set, falling back to default profiles: default
2018-06-24 21:14:27.307 INFO 17356 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]514646ef: startup date [Sun Jun 24 21:14:27 IST 2018]; root of context hierarchy
2018-06-24 21:14:29.976 INFO 17356 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-06-24 21:14:29.989 INFO 17356 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2018-06-24 21:14:30.127 WARN 17356 --- [ main] o.apache.activemq.broker.BrokerService : Memory Usage for the Broker (1024mb) is more than the maximum available for the JVM: 889 mb - resetting to 70% of maximum available: 622 mb
2018-06-24 21:14:30.422 INFO 17356 --- [ main] o.apache.activemq.broker.BrokerService : Using Persistence Adapter: MemoryPersistenceAdapter
2018-06-24 21:14:30.618 INFO 17356 --- [ JMX connector] o.a.a.broker.jmx.ManagementContext : JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
2018-06-24 21:14:30.675 INFO 17356 --- [ main] o.apache.activemq.broker.BrokerService : Apache ActiveMQ 5.14.5 (localhost, ID:DESKTOP-IK4A0TS-57046-1529855070442-0:1) is starting
2018-06-24 21:14:30.687 INFO 17356 --- [ main] o.apache.activemq.broker.BrokerService : Apache ActiveMQ 5.14.5 (localhost, ID:DESKTOP-IK4A0TS-57046-1529855070442-0:1) started
2018-06-24 21:14:30.688 INFO 17356 --- [ main] o.apache.activemq.broker.BrokerService : For help or more information please see: http://activemq.apache.org
2018-06-24 21:14:30.819 INFO 17356 --- [ main] o.a.activemq.broker.TransportConnector : Connector vm://localhost started
Message has been put to queue by sender
2018-06-24 21:14:31.279 INFO 17356 --- [ main] c.a.springboot.SpringBootApplicatioMain : Started SpringBootApplicatioMain in 5.127 seconds (JVM running for 10.015)

 

 

 

 

 

 

 

 

Leave a Comment

Bitnami