Working with Redis using Redisson

Redisson is a Java client library for Redis. Using it, you can manipulate, add, delete, edit data, and much more with a Redis server. In this tutorial, I will guide you through the basic operations with Redis using Redisson!

First, I will create a new Maven project:

with the Redisson dependency as an example:

Remember to start the Redis server up! You can refer to how to install Redis server using Docker here.

The RedissonExample class has the following initial content:

We will use the RedissonClient object to work with the Redis server and the create() static method of the Redisson class will help us create this new RedissonClient object.

By default, if the Redis server runs locally, you can use the static create() method with no parameters to connect to the Redis server:

but if you need to connect to a remote Redis server, we need to configure the information of that remote server. We will use the Config class to do this.

Redisson supports us to connect to a Redis server in many different deployment ways, for example:

  • Single node
  • Master with slave nodes
  • Sentinel nodes
  • Clustered nodes
  • Replicated nodes

You can choose how to connect using the Config object as follows:

In the example of this tutorial, I will use a single server with the following configuration:

As you can see, here I also have some more connection-related configurations including the connection pool, connection idle, and connection timeout (in ms). These are the necessary configurations so that we do not have to open and close the connection to the Redis server many times!

Now you can manipulate the Redis server using this RedissonClient object.

For example, you can save the value and then retrieve this value with the key as follows:

We call the getBucket() method to create or retrieve the information to be set. The getBucket() method will return us an RBucket object, this object can hold any object, then we will use the set() method of this RBucket object to set the value or update the value for it!

The following results:

You can also save information on a Map object and retrieve this Map object by key as follows:

The getMap() method will return an RMap object, so we can add, update or retrieve the key with its value.

Result:

Redis also supports us to save values only for a certain period of time.

To do this, for the Map object, you can use the getMapCache() method as follows:

Result:

As you can see, after 2 seconds, the data in the Map has expired.

There’s a lot more work with Redis that you can do with Redisson too. Depending on your needs, please research more!

5/5 - (1 vote)

Add Comment