Spring Tutorial – Messaging with Redis using the Spring

Messaging with Redis and Spring framework

Spring Tutorial – Messaging with Redis using the Spring 

Overview

Redis is a multiutility datastore which allows you to implement many different use cases – messaging application is one of them. When you create a messaging application with Redis, you are leveraging the twin benefits both Redis and the Spring Framework bring. Redis offers high speed operations, support for many different data types and atomic data while the Spring Framework is based on the principles of portability, productivity and consistency. The roles of Spring Framework and Redis in building a messaging application are clearly defined. While Redis acts as the datastore which is necessary for building the messaging application, the Spring Framework allows you to access the Redis API programmatically without too much effort. There is no need for learning new skills or boilerplate code.








What is Redis?

The Remote Dictionary Server, popularly known as Redis, is an in-memory datastore that can also write to disk for durability. It operates based on a client-server model. Redis offers two ways to persist data. Whichever way it conducts data operations, it is very fast. It supports many different data types and allows multiple client access at the same time.

Redis offers two ways to persist data: RDB and AOF. The RDB, though very fast, is relatively less reliable than AOF. The RDB captures data snapshots at specified intervals. The AOF, on the other hand, logs all data operations and executes the data operations every time the server restarts and reconstructs the original data set. When you query Redis, it always responds from in-memory.

Redis follows the client-server model and so, it listens to a TCP port and accepts commands. Since Redis commands are atomic, you can work on the same key from many different clients.

The Redis data model resembles the functional data types supported by programming languages which is suitable for the software developers. That way, it is different from any type of plain NoSQL key-value datastore or a relational database management system (RDBMS). Redis supports the following data types:

  • Strings
  • Lists
  • Sets
  • Sorted sets
  • Hashes

What are the advantages of Redis?

The main advantages of Redis are described below:

Exceptionally fast operations

Redis can set mind-boggling speeds for data operations. It can perform about 11000 SETs per second and 81000 GETs per second. You can also set internal benchmarks for service speeds by using the redis-benchmark utility. The redis-benchmark simulates all types of SETs/GETs performed by any number of clients while it sends the total number of queries.








Rich data type support

Software developers love Redis because it supports the data types they need for their day-to-day work. Redis makes it easy and simple for software developers to solve a variety of problems because of the variety of data types it supports.

Atomic operations

All Redis operations are atomic. This means that if more than one client accesses the Redis server concurrently, they all get the same updated values.

Multiutility tool

Since Redis is a multiutility tool, it allows you to complete many different use cases such as messaging-queues, caching, web sessions and web page hit counts and many more.

What is Spring Data Redis?

Redis, as might already be clear, is a popular datastore and many Spring-based applications access it. Behind such applications is the Spring Data umbrella open source project which makes it easier to build these applications. Spring Data Redis is a way for developers to access Redis programmatically and go about their jobs. From the software developers’ perspective, there is no need to invest time into learning new skills because the good old principles of the Plain Old Java Object (POJO) such as productivity, consistency, and portability, promoted by the Spring Framework, extend to Spring Data Redis. Developers do not need to work with boilerplate code required for interacting with Redis. They can easily work with Redis key-value datastores without requiring working with the low-level APIs that Redis offers. To interact with Redis, Spring Data Redis offers the generified template class named RedisTemplate, which is like the JDBC Template or Hibernate Template. As a developer, you are provided access to the RedisTemplate. To perform object-oriented interaction with Redis, you need access to the RedisTemplate main class.

Sample application & Configuration

This guide will help you to build applications using Spring Data Redis. It will demonstrate the messaging capabilities of Redis. We will follow the steps below to make the application run.

Environment set up:

We need to have the following things ready to complete the application.

Components to build:

Maven build script is the 1st component to write. Any other build tools can also be used to make this application work. But, here we will concentrate on maven build file (pom.xml).

Listing 1: Sample pom.xml file

[code]

<?xml version=”1.0″ encoding=”UTF-8″?>

<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/xsd/maven-4.0.0.xsd”>

<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework</groupId>

<artifactId>ex-messaging-redis</artifactId>

<version>0.1.0</version>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.9.RELEASE</version>

</parent>

<properties>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<optional>true</optional>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

<repositories>

<repository>

<id>spring-releases</id>

<name>Spring Releases</name>

<url>https://repo.spring.io/libs-release</url>

</repository>

</repositories>

</project>

[/code]

Now, we need to start the Redis server. Redis is an open source key-value data store. It is also having a messaging system. You need to download and unpack it. Then start the server using the following commands.

Listing 2: Unpack and start Redis server

[code]

$ wget http://download.redis.io/releases/redis-4.0.7.tar.gz

$ tar xzf redis-4.0.7.tar.gz

$ cd redis-4.0.7

$ make [/code]

[code]

$ src/redis-server

[/code]

After this we need to create a receiver for the messaging system. Any messaging system should at least have one publisher and one receiver.

Listing 3: Sample message receiver

[code]

package com.techalpine.redis;

import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

public class MsgReceiver {

private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);

private CountDownLatch msglatch;

@Autowired

public Receiver(CountDownLatch msglatch) {

this.msglatch = msglatch;

}

public void receiveMsg(String msg) {

LOGGER.info(“Received Message <” + msg + “>”);

msglatch.countDown();

}

} [/code]

Now, following is the main application to run the application. This sample contains the main components to write the code.

Listing 4: Sample main application

[code]

public static void main(String[] args) throws InterruptedException {

ApplicationContext redisctx = SpringApplication.run(RedisApplication.class, args);

StringRedisTemplate redistemplate = redisctx.getBean(StringRedisTemplate.class);

CountDownLatch redislatch = redisctx.getBean(CountDownLatch.class);

LOGGER.info(“Sending Redis messages…”);

redistemplate.convertAndSend(“Hello”, “I am from Redis”);

redislatch.await();

System.exit(0);

}

[/code]

You can run the application from command prompt after building it using Maven.








Conclusion:

Given the current context of software development, Redis provides exactly what is needed. At a time when Agile software development is gaining prominence, fast data operations, portability, consistency, developer productivity and swift software roll-outs are important. Spring Data Redis fulfils such demands. Probably, developer productivity and support for different use cases are its highlights. Organizations do not want to spend a lot of time on developers learning new skills, that is why, Spring Redis allows developers to start development without needing to know Redis in-depth. It supports quality and swift software development. Redis and Spring Framework constitutes a powerful combination.

 

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share