Featured

Reactjs CRUD Firebase Realtime Database Example

Tutorial: “Reactjs CRUD Firebase Realtime Database Example”

The Firebase Realtime Database is a cloud-hosted NoSQL database that lets you store and sync data between your users in realtime. In the tutorial, I introduce how to build an “Reactjs CRUD Firebase Realtime Database Example ” project to do CRUD operation: POST/GET/PUT/DELETE requests with step by step coding examples.

– I draw a fullstack overview diagram architecture from Reactjs frontend to Firebase Realtime Database.
– I illustrate details about react-firebase CRUD operations.
– I implement Reactjs application to do CRUD request (Post/Get/Put/Delete) to Firebase Realtime database.

Related posts:


Continue reading “Reactjs CRUD Firebase Realtime Database Example”

Featured

Reactjs JWT Authentication Example – Reactjs Login Authentication Example

Tutorial: ” Reactjs JWT Token Authentication Example – Reactjs Login Authentication Example ”

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. So in the tutorial, I introduce how to implement an application “Reactjs JWT token Authentication Example – Reactjs Login Authentication Example ” with details step by step and 100% running sourcecode.

– I give you an Epic of the application, a fullstack excutive flow from frontend to backend with overall architecture diagram.
– I give you a layer diagram of Reactjs JWT Application.
– I give you an implementatin of security backend sourcecode (SpringBoot + Nodejs JWT RestAPIs).
– I guide you step by step how to develop a Reactjs JWT Authentication application.
– Finally, I do an integrative testing from Reactjs JWT Authentication application to Backend Security RestAPIs

Related posts:


Continue reading “Reactjs JWT Authentication Example – Reactjs Login Authentication Example”

Featured

Django Angular 10 CRUD Example – MySQL + Django Rest Framework Tutorial

Tutorial: Django Angular 10 CRUD Example – Fullstack: Angular 10 + Django Rest Framework + MySQL.

Django is a Python-based free and open-source web framework that follows the model-template-view architectural pattern. Angular is a TypeScript-based open-source web application framework led by the Angular Team at Google. In the tutorial, I introduce how to build a Angular Django CRUD RestAPIs Fullstack Project with POST/GET/PUT/DELETE requests using Django Rest Framework and MySQL database with step by step coding examples.

Related posts:


Continue reading “Django Angular 10 CRUD Example – MySQL + Django Rest Framework Tutorial”

Featured

Spring Boot Pagination and Filter Example

Tutorial: “Spring Boot Pagination and Filter Sorting Example | Spring RestAPIs + Spring JPA using Pageable & Sort object requests”

When we have a large dataset and we want to present it to the user in smaller chunks, pagination and sorting is often helpful solution. So in the tutorial, I introduce how to build “Spring Boot Pagination and Filter Sorting Example” use Spring JPA APIs of PagingAndSortingRepository to do the task with SpringBoot project example.

Related posts:


Continue reading “Spring Boot Pagination and Filter Example”

Featured

Angular 10 + Nodejs JWT Token Based Authentication with MySQL Example – Express RestAPIs + JWT + BCryptjs + Sequelize

“How to implement Angular 10 + Nodejs JWT Token Based Authentication with MySQL Example?” is always a big common question in development world? So in the tutorial, I guide you very clearly how to build a full stack example to demonstrate an JWT Authentication flow from Angular (signup & signin with by JWT Token) to backend: Nodejs and database MySQL.

Related posts:


Now let’s go!

Continue reading “Angular 10 + Nodejs JWT Token Based Authentication with MySQL Example – Express RestAPIs + JWT + BCryptjs + Sequelize”

Featured

SpringBoot Token Based Authentication Example – MySQL + JWT+ Spring JPA + RestAPIs

“How to build SpringBoot Token Based Authentication Example?” is one of the most common questions for Java development world. So in the tutorial, I will introduce how to build it with clearly architecture and coding examples.

Related posts:


Continue reading “SpringBoot Token Based Authentication Example – MySQL + JWT+ Spring JPA + RestAPIs”

RabbitMQ Topic Exchange Spring Boot Example

– Tutorial: “RabbitMQ Topic Exchange Spring Boot Example” + Github Sourcecode

Topic exchange is powerful and can behave like other exchanges. In the tutorial, I show you how to build an example “RabbitMQ Topic Exchange Spring Boot Example” with github sourcecode.

* Technologies:
– Java 8
– Maven
– Spring Tool Suite
– Spring Boot
– RabbitMQ

RabbitMQ Topic Exchange

routing_key of messages sent to a topic exchange must be a list of words, delimited by dots, example:

#.error
*.prod.*
sys.#

Note:
* (star) must be an exactly one word.
# (hash) can be zero or more words.

Springboot RabbitMQ Topic Exchange Architecture
Springboot RabbitMQ Topic Exchange Architecture

With the above topic exchange design,
– when we send a message with routing key: sys.dev.info, it will just be delivered to Q1.
– when we send a message with routing key: app.prod.error, it will just be delivered to Q2.
– when we send a message with routing key: sys.test.error, it will be delivered to both queues {Q1, Q2}.

Topic exchange is strong tool and it can act as other exchanges as below:

– When a queue is bound with “#” (hash) binding key – it is as an fanout exchange.
– When don’t use * & # in bindings, it will behave as a direct exchange.

Practices – RabbitMQ Topic Exchange Spring Boot Example

In the tutorial, we create 2 SpringBoot project as below:

Springboot RabbitMQ Topic Project Structures
Springboot RabbitMQ Topic Project Structures

* Step to do:
– Create SpringBoot projects
– Define data model
– Implement RabbitMq Producer
– Implement RabbitMq consumer
– Run and check results

Create SpringBoot Projects

Using SpringToolSuite, create 2 SpringBoot projects, then add need dependency spring-boot-starter-amqp:


<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

Define Java Data Model

Create Log data model for both projects:


package com.loizenjava.rabbitmq.model;

public class Log {
	private String content;
	private String routingKey;
	
	public Log(){};
	
	public Log(String content, String routingKey){
		this.content = content;
		this.routingKey = routingKey;
	}
	
	public String getContent(){
		return this.content;
	}
	
	public void setContent(String content){
		this.content = content;
	}
	
	public String getRoutingKey(){
		return this.routingKey;
	}
	
	public void setRoutingKey(String routingKey){
		this.routingKey = routingKey;
	}
	
	@Override
	public String toString() {
		return String.format("{content = %s, routingKey = %s}", content, routingKey);
	}
}

Configure SpringBoot RabbitMQ Producer – RabbitMQ Topic Exchange Spring Boot Example


package com.loizenjava.rabbitmq.config;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfig {
	
    @Bean
    public MessageConverter jsonMessageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    
    public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
}

Open application.properties, add configuration:


spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
jsa.rabbitmq.exchange=jsa.exchange.logs
jsa.rabbitmq.queue=jsa.queue
jsa.rabbitmq.routingkey=jsa.routingkey

Implement SpringBoot RabbitMq Producer – RabbitMQ Topic Exchange Spring Boot Example


package com.loizenjava.rabbitmq.producer;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.loizenjava.rabbitmq.model.Log;

@Component
public class Producer {
	
	@Autowired
	private AmqpTemplate amqpTemplate;
	
	@Value("${jsa.rabbitmq.exchange}")
	private String exchange;
	
	public void produce(Log logs){
		String routingKey = logs.getRoutingKey();
		amqpTemplate.convertAndSend(exchange, routingKey, logs);
		System.out.println("Send msg = " + logs);
	}
}

Implement SpringBoot RabbitMQ Producer Client


package com.loizenjava.rabbitmq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.loizenjava.rabbitmq.model.Log;
import com.loizenjava.rabbitmq.producer.Producer;

@SpringBootApplication
public class SpringRabbitMqProducerApplication  implements CommandLineRunner{

	public static void main(String[] args) {
		SpringApplication.run(SpringRabbitMqProducerApplication.class, args);
	}
	
	@Autowired
	Producer producer;

	@Override
	public void run(String... args) throws Exception {
		
		/**
		 *  1
		 */
		String content = "2014-03-05 10:58:51.1  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52";
		String routingKey = "sys.dev.info";
		
		// send to RabbitMQ
		producer.produce(new Log(content, routingKey));
		
		/**
		 *  2
		 */
		content = "2017-10-10 10:57:51.10 ERROR in [email protected]:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]";
		routingKey = "sys.test.error";
		
		// send to RabbitMQ
		producer.produce(new Log(content, routingKey));
		
		/**
		 *  3
		 */
		content = "2017-10-10 10:57:51.112  ERROR java.lang.Exception: java.lang.Exception";
		routingKey = "app.prod.error";
		
		// send to RabbitMQ
		producer.produce(new Log(content, routingKey));
	}
}

Configure SpringBoot RabbitMq Consumer


package com.loizenjava.rabbitmq.config;

import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfig {
	
    @Bean
    public MessageConverter jsonMessageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    
    @Bean
    public SimpleRabbitListenerContainerFactory jsaFactory(ConnectionFactory connectionFactory,
            SimpleRabbitListenerContainerFactoryConfigurer configurer) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        factory.setMessageConverter(jsonMessageConverter());
        return factory;
    }
}

Open application.properties, add configuration:


spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
jsa.rabbitmq.queue=jsa.logs.sys
#jsa.rabbitmq.queue=jsa.logs.prod.error

Implement Spring Boot Consumer


package com.loizenjava.rabbitmq.consumer;

import org.apache.commons.logging.Log;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


@Component
public class Consumer {
	
	@RabbitListener(queues="${jsa.rabbitmq.queue}", containerFactory="jsaFactory")
    public void recievedMessage(Log logs) {
        System.out.println("Recieved Message: " + logs);
    }
}

Run and Check Results

– Setup RabbitMq Exchange, Queues:

Enable rabbitmq_management by cmd: rabbitmq-plugins enable rabbitmq_management --online

Then go to: http://localhost:15672 -> login with user/password: guest/guest

Spring Boot RabbitMQ Topic Exchange Connection
Spring Boot RabbitMQ Topic Exchange Connection

Add exchange:

Go to http://localhost:15672/#/exchanges, add exchange: jsa.exchange.logs

Springboot Rabbitmq Topic Exchange - Create Exchange
Springboot Rabbitmq Topic Exchange – Create Exchange

– Add Queue:

Go to http://localhost:15672/#/queues, add 2 queues: jsa.logs.sys, jsa.logs.prod.error.

SpringBoot RabbitMQ Topic 2 Queue 1
SpringBoot RabbitMQ Topic 2 Queue 1

– Binding the queues with above exchange:

SpringBoot RabbitMQ Topic Exchange Bindling
SpringBoot RabbitMQ Topic Exchange Bindling

Run & Check Results

– Run SpringBoot-RabbitMQ-Producer with commandline mvn spring-boot:run.

– Console’s logs:


Send msg = {content = 2014-03-05 10:58:51.1  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52, routingKey = sys.dev.info}
Send msg = {content = 2017-10-10 10:57:51.10 ERROR in [email protected]:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]], routingKey = sys.test.error}
Send msg = {content = 2017-10-10 10:57:51.112  ERROR java.lang.Exception: java.lang.Exception, routingKey = app.prod.error}

– See queues’ status:

SpringBoot RabbitMQ Topic Message Queue After Sending
SpringBoot RabbitMQ Topic Message Queue After Sending

– Run Spring-Boot-RabbitMQ-Consumer which listen to jsa.logs.sys queue with configuration: jsa.rabbitmq.queue=jsa.logs.sys:

– Console’s logs:


Recieved Message: {content = 2014-03-05 10:58:51.1  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52, routingKey = sys.dev.info}
Recieved Message: {content = 2017-10-10 10:57:51.10 ERROR in [email protected]:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]], routingKey = sys.test.error}

– See queues’s status:

SpringBoot RabbitMQ Topic After Consume in jsa.logs_.sys_
SpringBoot RabbitMQ Topic After Consume in jsa.logs_.sys_

– Run Spring-Boot-RabbitMQ-Consumer which listen to jsa.logs.prod.error queue with configuration: jsa.rabbitmq.queue=jsa.logs.prod.error:

– Console’s Logs:


Recieved Message: {content = 2017-10-10 10:57:51.10 ERROR in [email protected]:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]], routingKey = sys.test.error}
Recieved Message: {content = 2017-10-10 10:57:51.112  ERROR java.lang.Exception: java.lang.Exception, routingKey = app.prod.error}

– See queues’s status:

SpringBoot RabbitMQ Topic After Consume in jsa.logs_.prod_.error_
SpringBoot RabbitMQ Topic After Consume in jsa.logs_.prod_.error_

Read More

Related posts:


– Reference Link: RabbitMQ Topic Exchange

Source Code

SpringBoot-RabbitMQ-Producer
Spring-RabbitMQ-Consumer

Spring Boot Batch Restart Job Example

– Tutorial: “Spring Boot Batch Restart Job Example with SpringBoot RestAPI Implementation”

SpringBatch provides a restartable mechanics with a Job. So in the tutorial, I will present to you the principle of this function with SpringBoot.

Continue reading “Spring Boot Batch Restart Job Example”

RabbitMQ Publish/Subscribe Java Example + SpringBoot

– Tutorial “Rabbitmq Publish/Subscribe Java Example with SpringBoot”

In the tutorial, I guide how to create Spring RabbitMq Publish/Subcribe pattern by using fanout exchanges of RabbitMQ and SpringBoot.

Spring RabbitMq Publish/Subcribe pattern – RabbitMQ Publish/Subscribe Java Example + SpringBoot

We create a Publisher, and 3 Subcribers and using fanout exchanges of RabbitMQ for create a Publish/Subcribe Pattern System:

Spring RabbitMQ Publish Subscribe Pattern Architechture - RabbitMQ Publish/Subscribe Java Example + SpringBoot
Spring RabbitMQ Publish Subscribe Pattern Architechture

* Flow messages:

– Publisher will send messages to the fanout exchange.
– The fanout exchange routes messages to all of the queues that are bound to it and the routing key is ignored.
– Subcribers instances recieves messages from the queues.

Practice – Rabbitmq Publish/Subscribe Java Example + SpringBoot

* Technologies:

– Java 8
– Maven 3.6.1
– Spring Tool Suite
– Spring Boot
– RabbitMQ

We create 2 SpringBoot projects {Publisher, Subcriber}:

Spring RabbitMQ Publish Subscribe Pattern Project Structures - RabbitMQ Publish/Subscribe Java Example + SpringBoot
Spring RabbitMQ Publish Subscribe Pattern Project Structures

* Step to do:
– Create SpringBoot projects
– Create Publiser/Subcriber
– Setup RabbitMQ exchange, queues
– Run and check results

Create SpringBoot projects – RabbitMQ Publish/Subscribe Java Example + SpringBoot

Using Spring Tool Suite, create 2 Spring Starter Projects then add amqp dependency for both of them:


<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

– With Spring-Rabbit-MQ-Publiser, we add more web dependency for creating RestController:


<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Create SpringBoot RabbitMQ Publisher – RabbitMQ Publish/Subscribe Java Example + SpringBoot

– Add RabbitMq configuration:


spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
jsa.rabbitmq.exchange=jsa.fanout

– Implement RabbitMQ Publisher:


package com.loizenjava.rabbitmq.publisher;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Publisher {
	
	@Autowired
	private AmqpTemplate amqpTemplate;
	
	@Value("${jsa.rabbitmq.exchange}")
	private String exchange;
	
	public void produceMsg(String msg){
		amqpTemplate.convertAndSend(exchange, "",msg);
		System.out.println("Send msg = " + msg);
	}
}

– Implement a sending RestAPI:


package com.loizenjava.rabbitmq.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.loizenjava.rabbitmq.publisher.Publisher;

@RestController
public class WebController {
	
	@Autowired
	Publisher publisher;
	
	@RequestMapping("/send")
	public String sendMsg(@RequestParam("msg")String msg){
		publisher.produceMsg(msg);
		return "Done";
	}
}

Create Spring RabbitMQ Subcriber

– Add RabbitMq configuration:


spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
jsa.rabbitmq.queue=jsa.queue.1

– Create RabbitMQ Subcriber:


package com.loizenjava.rabbitmq.subcriber;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class Subcriber {

	@RabbitListener(queues="${jsa.rabbitmq.queue}")
    public void recievedMessage(String msg) {
        System.out.println("Recieved Message: " + msg);
    }
}

Setup RabbitMQ Exchange, Queues – RabbitMQ Publish/Subscribe Java Example + SpringBoot

Enable rabbitmq_management by cmd: rabbitmq-plugins enable rabbitmq_management --online

Go to: http://localhost:15672. Then login with user/password: guest/guest.

– Add an RabbitMQ Exchange:

Create a fanout exchange: jsa.fanout

Spring RabbitMQ Publish Subscribe Pattern Create Exchanges - RabbitMQ Publish/Subscribe Java Example + SpringBoot
Spring RabbitMQ Publish Subscribe Pattern Create Exchanges

– Add RabbitMQ Queues:

Create 3 RabbitMq queues {jsa.queue.1, jsa.queue.2, jsa.queue.3}:

Spring RabbitMQ Publish Subscribe Pattern Create 3 Queues
Spring RabbitMQ Publish Subscribe Pattern Create 3 Queues

Binding all above queues with the fanout exchange jsa.fanout:

Spring RabbitMQ Publish Subscribe Pattern Binding Queue with Exchanges
Spring RabbitMQ Publish Subscribe Pattern Binding Queue with Exchanges

Run and Check results

Build 2 SpringBoot projects {Publisher, Subcriber} with the commandline: mvn clean install.

Run Publisher with commandline: mvn spring-boot:run, then send a message by a request: localhost:8080/send?msg=Hello World!

– See status of the Queues:

Spring RabbitMQ Publish Subscribe Pattern Queue Status After Send First Message
Spring RabbitMQ Publish Subscribe Pattern Queue Status After Send First Message

Run 3 Subcriber instances which different configured values of jsa.rabbitmq.queue: {jsa.queue.1, jsa.queue.2, jsa.queue.3}.

See console logs of each Subcriber instances, we got the same message: ‘Recieved Message: Hello World!’.

– Again, check status of the queues:

Spring RabbitMQ Publish Subscribe Pattern Consumer Messages
Spring RabbitMQ Publish Subscribe Pattern Consumer Messages

– All messages has been consumed by Subcribers.

Read More

Related posts:


– Reference Link: RabbitMQ Publish/Subscribe

SourceCode – RabbitMQ Publish/Subscribe Java Example + SpringBoot

SpringBoot-RabbitMQ-Publisher
SpringBoot-RabbitMQ-Subcriber

Spring Boot RabbitMQ Multiple Consumers Example

– Tutorial: “Spring Boot Rabbitmq Multiple Consumers Example using RabbitMq Exchange to Exchange Topology – Spring Boot Rabbitmq Multiple Listeners”

In the post, I show you how to work with SpringBoot RabbitMq Exchange to Exchange Topology to develop an example “Rabbitmq Multiple Queues and Multiple Listeners”.

* Technologies:

– Java 8
– Maven
– Spring Tool Suite
– Spring Boot
– RabbitMq

RabbitMq Exchange to Exchange – Spring Boot Rabbitmq Multiple Consumers Example

We create a RabbitMQ topology with 2 topic exchanges and 3 binding queues:

Spring Boot Rabbitmq Multiple Queue - with Exchange Topic Architecture
Spring Boot Rabbitmq Multiple Queue – with Exchange Topic Architecture

Scenarios with above design:
– when we send a message with routing key: sys.prod.info, it will be delivered by path: X1 -> Q3.
– when we send a message with routing key: app.prod.error, it will be delivered by path: X1 -> X2 -> {Q2, Q3}.
– when we send a message with routing key: sys.test.error, it will be delivered by path: X1 -> X2 -> Q1.

Practices – Spring Boot Rabbitmq Multiple Consumers Example

In the tutorial, we create 2 SpringBoot project as below:

Spring Boot RabbitMQ Topic - Project Structure
Spring Boot RabbitMQ Topic – Project Structure

– Step to do:
– Create SpringBoot projects
– Define data model
– Implement RabbitMq Producer
– Implement RabbitMq consumer
– Run and check results

Create SpringBoot projects

Using SpringToolSuite, create 2 SpringBoot projects, then add need dependency spring-boot-starter-amqp:


<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

Define Spring Data Model – Spring Boot Rabbitmq Multiple Consumers Example

Create Log data model for both projects:


package com.loizenjava.rabbitmq.model;
 
public class Log {
	private String content;
	private String routingKey;
	
	public Log(){};
	
	public Log(String content, String routingKey){
		this.content = content;
		this.routingKey = routingKey;
	}
	
	public String getContent(){
		return this.content;
	}
	
	public void setContent(String content){
		this.content = content;
	}
	
	public String getRoutingKey(){
		return this.routingKey;
	}
	
	public void setRoutingKey(String routingKey){
		this.routingKey = routingKey;
	}
	
	@Override
	public String toString() {
		return String.format("{content = %s, routingKey = %s}", content, routingKey);
	}
}

Now it’s time for implementation. Let’s go!

Configure SpringBoot RabbitMq Producer – Spring Boot Rabbitmq Multiple Consumers Example


package com.loizenjava.rabbitmq.config;
 
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class RabbitMqConfig {
	
    @Bean
    public MessageConverter jsonMessageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    
    public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
}

Open application.properties, add configuration:


spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
jsa.rabbitmq.exchange=jsa.exchange.logs
jsa.rabbitmq.queue=jsa.queue
jsa.rabbitmq.routingkey=jsa.routingkey

Implement SpringBoot RabbitMq Producer


package com.loizenjava.rabbitmq.producer;
 
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import com.loizenjava.rabbitmq.model.Log;
 
@Component
public class Producer {
	
	@Autowired
	private AmqpTemplate amqpTemplate;
	
	@Value("${jsa.rabbitmq.exchange}")
	private String exchange;
	
	public void produce(Log logs){
		String routingKey = logs.getRoutingKey();
		amqpTemplate.convertAndSend(exchange, routingKey, logs);
		System.out.println("Send msg = " + logs);
	}
}

Implement SpringBoot RabbitMQ Producer Client


package com.loizenjava.rabbitmq;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
import com.loizenjava.rabbitmq.model.Log;
import com.loizenjava.rabbitmq.producer.Producer;
 
@SpringBootApplication
public class SpringRabbitMqProducerApplication  implements CommandLineRunner{
 
	public static void main(String[] args) {
		SpringApplication.run(SpringRabbitMqProducerApplication.class, args);
	}
	
	@Autowired
	Producer producer;
 
	@Override
	public void run(String... args) throws Exception {
		
		/**
		 *  1
		 */
		String content = "2014-03-05 10:58:51.1  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52";
		String routingKey = "sys.dev.info";
		
		// send to RabbitMQ
		producer.produce(new Log(content, routingKey));
		
		/**
		 *  2
		 */
		content = "2017-10-10 10:57:51.10 ERROR in [email protected]:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]";
		routingKey = "sys.test.error";
		
		// send to RabbitMQ
		producer.produce(new Log(content, routingKey));
		
		/**
		 *  3
		 */
		content = "2017-10-10 10:57:51.112  ERROR java.lang.Exception: java.lang.Exception";
		routingKey = "app.prod.error";
		
		// send to RabbitMQ
		producer.produce(new Log(content, routingKey));
	}
}

Configure SpringBoot RabbitMQ Consumer


package com.loizenjava.rabbitmq.config;
 
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class RabbitMqConfig {
	
    @Bean
    public MessageConverter jsonMessageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    
    @Bean
    public SimpleRabbitListenerContainerFactory jsaFactory(ConnectionFactory connectionFactory,
            SimpleRabbitListenerContainerFactoryConfigurer configurer) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        factory.setMessageConverter(jsonMessageConverter());
        return factory;
    }
}

Open application.properties, add configuration:


spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
jsa.rabbitmq.queue=jsa.queue.logs.application-error
#jsa.rabbitmq.queue=jsa.queue.logs.system-error
#jsa.rabbitmq.queue=jsa.queue.logs.production

Implement SpringBoot RabbitMQ Consumer


package com.loizenjava.rabbitmq.consumer;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import com.loizenjava.rabbitmq.model.Log;

@Component
public class Consumer {
	
    @RabbitListener(queues="${jsa.rabbitmq.queue}", containerFactory="jsaFactory")
    public void recievedMessage(Log logs) {
        System.out.println("Recieved Message: " + logs);
    }
}

Run and Check Results – Spring Boot Rabbitmq Multiple Consumers Example

– Setup RabbitMq exchange, queues:

Enable rabbitmq_management by cmd: rabbitmq-plugins enable rabbitmq_management --online. Then go to: http://localhost:15672 -> login with user/password: guest/guest.

– Add RabbitMQ exchanges:

Go to http://localhost:15672/#/exchanges, add 2 exchanges: {jsa.exchange.logs, jsa.exchange.logs.error}.

Spring Boot RabbitMQ Topic Connection
Spring Boot RabbitMQ Topic Connection

– Add RabbitMQ Queue:

Go to http://localhost:15672/#/queues, add 3 queues: {jsa.queue.logs.application-error, jsa.queue.logs.system-error, jsa.queue.logs.production}.

Spring Boot Rabbitmq Topic Create Exchange
Spring Boot Rabbitmq Topic Create Exchange

– Binding the queues & exchanges:

Spring Boot RabbitMQ Topic 2 Queue 1
Spring Boot RabbitMQ Topic 2 Queue 1
SpringBoot RabbitMQ Topic Exchange Bindling -
SpringBoot RabbitMQ Topic Exchange Bindling

– Run SpringBoot-RabbitMQ-Producer with commandline mvn spring-boot:run,

-> Console’s logs:


Send msg = {content = 2014-03-05 10:58:51.1  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52, routingKey = sys.prod.info}
Send msg = {content = 2017-10-10 10:57:51.10 ERROR in [email protected]:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]], routingKey = sys.test.error}
Send msg = {content = 2017-10-10 10:57:51.112  ERROR java.lang.Exception: java.lang.Exception, routingKey = app.prod.error}

– See queues’ status:

Springboot Rabbitmq Topic After Consume in jsa_logs_sys
Springboot Rabbitmq Topic After Consume in jsa_logs_sys

– Run SpringBoot-RabbitMQ-Consumer which listen to jsa.queue.logs.application-error queue with configuration:

jsa.rabbitmq.queue=jsa.queue.logs.application-error:

– Console’s logs:


Recieved Message: {content = 2017-10-10 10:57:51.112  ERROR java.lang.Exception: java.lang.Exception, routingKey = app.prod.error}

– Run SpringBoot-RabbitMQ-Consumer which listen to jsa.queue.logs.system-error queue with configuration:

jsa.rabbitmq.queue=jsa.queue.logs.system-error:

-> Console’s logs:


Recieved Message: {content = 2017-10-10 10:57:51.10 ERROR in [email protected]:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]], routingKey = sys.test.error}

– Run SpringBoot-RabbitMQ-Consumer which listen to jsa.queue.logs.production queue with configuration:

jsa.rabbitmq.queue=jsa.queue.logs.production:

– Console’s logs:


Recieved Message: {content = 2014-03-05 10:58:51.1  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52, routingKey = sys.prod.info}
Recieved Message: {content = 2017-10-10 10:57:51.112  ERROR java.lang.Exception: java.lang.Exception, routingKey = app.prod.error}

Read More

Related posts:


– Reference Link: RabbitMQ Exchange Topic

SourceCode

SpringBoot-RabbitMQ-Producer
SpringBoot-RabbitMQ-Consumer