Web Programming TutorialsHow to work with Java application and Redis Caching?

How to work with Java application and Redis Caching?

In today’s world, the performance of the application is very critical for business. All your applications, be it a product, enterprise level distributed application or standalone application, performance is the ultimate keyword for success. So, the application and its storage have to be designed carefully. ‘Redis’ plays an important role here. It is an open source, in-memory key-value store for building high performance, scalable applications. In this article, we will explore how Redis can be used with Java applications.

What is Redis?

Now, let us explore a bit more about Redis. It is an open source and in-memory data structure store. Redis can be used for the following purposes.

  • Database
  • Cache
  • Message broker

It can store strings, lists, sets, hashes. It offers interesting features like built-in replication, LRU eviction, transactions, on-disk persistence and high availability. Redis Sentinel is another important component to monitor Redis master and slave instances. It offers automatic failover in a clustered environment. Redis is written in ANSI C. It can be used with most of the languages. Redis is recommended to deploy in Linux environment. Microsoft is also having windows build for Redis deployment.

Redis features:

Following are some of the most important Redis features to learn. We will explore some of them in our article. We will mainly focus on the in-memory caching mechanism.

  • In-memory caching
  • Pub/Sub support
  • Transactions management
  • Master-slave asynchronous replication
  • Auto-reconnection support
  • Lua scripting
  • Keys with a limited time-to-live
  • Atomic operations
  • LRU eviction of keys
  • Automatic failover
  • On disc persistence
  • Built-in replication
  • Data structure support for strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglog, geospatial indexes

Download and Installation:

In this section, we will discuss the download and installation part of Redis server in details.

Redis can be downloaded by the following two ways.

  • Download from the latest Redis tar ball from redis.io
  • Download from this URL

You can also have a look at https://redis.io/download for more details and explore other interesting options.

The best option to install Redis is by compiling it from its source and run it. It is easier as Redis does not have any dependencies except GCC compiler and libc.

Now, we need to compile Redis and test it. Following commands are used for the compilation purpose.

Listing 1: Compiling Redis using the following commands

wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make

Once the compilation is successful, the source directory (src) in the Redis distribution will be populated with different necessary executable. Following are the list of the widely used executable present in the directory. There are some more executable, but those are not frequently used.

  • Redis Server (redis-server)
  • Redis Sentinel for monitoring and failover (redis-sentinel)
  • Redis command line interface (redis-cl)

After this, put ‘redis-server’ and ‘redis-cli’ in the proper place and add the location/path in your ‘PATH’ environment variable. The other option is to use ‘sudo make install’ command. Now, you can use those executable without specifying the complete path.
Now, we need to start the Redis server. Just use the following command to start the server.

$ redis-server

This is the simple command to start the Redis server with default configuration. A default configuration is sufficient for development and testing purpose. But, we need to use a separate configuration file (redis.conf) for the production environment. Full path of the configuration file should be mentioned as following.

$ redis-server /etc/redis.conf

After this, it is the time to test the Redis server. We need to ensure that the server is running properly and it can be used from our Java application. Here, we will use redis-cli utility to test the server. Following is the command. The response will be ‘PONG’, and it indicates that the server is responding to the input command.

$ redis-cli  ping
PONG

By default, Redis runs at port 6379 (localhost). For a clustered environment, the port is 16379.

Redis client libraries

At this point, the Redis server is installed successfully and running properly. Redis CLI is good enough for interacting with the server, but it is not useful for application development. So, we need some Redis client library to access the Redis server from our application.

  • Jedis: Jedis is a client library in Java for Redis in-memory data structure store. Jedis is small, faster and fully compatible with Redis 2.8.x, 3.x.x and above.
  • Lettuce: Lettuce is another choice for Redis Java client library. It is non-blocking and supports asynchronous and synchronous data access.

There are some more Java client libraries available for Redis connection. But, these are widely used by Java and Spring-based applications. In this article, we will talk about ‘Jedis’ as the client library for our Java application.

Jedis client library can be downloaded from this link. Please ensure, that you have downloaded the latest stable version. Once the download is complete, put the jar (jedis.jar) in your classpath.

Writing the application:

In this section, we will check each and every step to build a Java application using Redis in-memory data structure store and Jedis client library.

Step 1: We need to add one maven dependency for Jedis client library. You can use any other version.

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.2.1</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>

Step 2: Here we will write a simple Java application to connect to a Redis server.

package com.eduonix.redis.example
import redis.clients.jedis.Jedis; 
public class RedisJavaExample { 
   public static void main(String[] args) { 
      //Connect to Redis server using localhost
      Jedis jedis = new Jedis("localhost"); 
      System.out.println("Connection successful"); 
	  
      //Checking server
      System.out.println("Getting response from the server: "+jedis.ping()); 
   } 
}

 

Now, we will compile and run the application by using the following commands.

$javac RedisJavaExample.java 

$java RedisJavaExample

 

The output will show the following result. First, it will connect to the server and a response will be returned by the server.

Connection successful

Getting response from the server: PONG

Step 3: In this section, we will explore some more features of Redis by coding examples.

package com.eduonix.redis.example
import redis.clients.jedis.Jedis; 

public class RedisCacheExample { 
   public static void main(String[] args) { 
      //Connect to Redis server using localhost
      Jedis jedis = new Jedis("localhost"); 
      System.out.println("Connection successful"); 	  
      //set string data in redis cache
      jedis.set("eduonix", "Redis cache tutorial"); 
      //Retrieve the string value from the cache 
      System.out.println("Stored data in cache: "+ jedis.get("eduonix")); 
   } 
}

 

Now, compile and run the application.

$javac RedisCacheExample.java 

$java RedisCacheExample

The output will show the following result.

Connection successful
Stored data in cache: Redis cache tutorial

In this example, we have stored strings in Redis cache. String is the most common values stored in Redis cache. Redis server stores it as a key-value pair. Here the variable named ‘cachedResponse’ holds the value with expiration details. This is the simplest and fast caching layer, which supports HTTP requests to your web applications. It is very efficient for supporting basic caching requirement.

Conclusion:

Redis in-memory data structure store is widely used in various applications. It is the simple and fast in-memory store, which can be accessed easily with minimum configuration. If you are keen to know more about Redis then you can opt for this free Eduonix course Learn Redis from Scratch. On the other hand, Jedis client library is very useful to connect Java-based applications with the Redis server. Jedis configuration is also very simple as explained in this article. Hope, this article will help you to implement your own caching layer.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -