How to use Redis with Spring in Java
Tags: redis, java, spring, cache
Published: 2020-10-30 15:25:16

In a Java Project, you must include the following dependencies to use Redis database:

##### 1.Use the Spring Data redis

*with Maven:*
```xml
<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>2.3.4.RELEASE</version>
</dependency>
``` 
*with Gradle:*

```
compile group: 'org.springframework.data', name: 'spring-data-redis', version: '2.3.4.RELEASE'

``` 

##### 2.Use Jedis as client connector

*with Maven:*

```xml
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.3.0</version>
</dependency>
``` 

*with Gradle:*

```
compile group: 'redis.clients', name: 'jedis', version: '3.3.0'
``` 

After that, in your project create a Redis Context File to declare objects which define the connections settings to Redis server:


```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd">
  
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"
          p:max-total="${redis.config.pool.maxTotal}" />
  
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.config.hostname}" 
          p:port="${redis.config.port}" 
          p:use-pool="true">
        <constructor-arg ref="jedisPoolConfig"/>
    </bean>
  
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" 
          p:connection-factory-ref="jedisConnectionFactory" 
          p:enable-transaction-support="true"/>
  
    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" 
          p:connection-factory-ref="jedisConnectionFactory" 
          p:enable-transaction-support="true"/>  
</beans>
``` 


Include some properties defined in the bean objects to the application.properties file:


```
#Redis Config
redis.config.hostname=127.0.0.1
redis.config.port=6379
redis.config.pool.maxTotal=5
``` 


In your persistence context or main spring-context, inject the RedisTemplate bean into the DAO bean object that you want to use Redis cache, for example in a TransactionDao object:

*Context:*
```xml
<bean id="transactionDao" class="com.juanc4milo.persistence.dao.TransactionDao">
	<property name="redisTemplate" ref="redisTemplate"/>
</bean>
``` 

*TransactionDao class:*
```java
@Autowired
private RedisTemplate<String, Transaction> redisTemplate
```

Then create an instance of the ValueOperations class to operate with the Redis database.

To set a value in database use the method *SET* from ValueOperations class, like:


```java
valueOperation.set(<<key>>,<<value>>);
``` 

The transaction ID will be the key in Redis database, and the entire object Transaction will be the value. After that, you could set the expiration time in seconds, minutes, hours, etc.

```java
ValueOperations<String, Transaction> valueOperation = redisTemplate.opsForValue();
valueOperation.set(transaction.getId(), transaction);
redisTemplate.expire(transaction.getId(), 3600, TimeUnit.SECONDS);
```

Redis allows cache of different types of values, such as:

* Values
* Sets
* Sorted sets
* Hashes
* Lists

To get the data from Redis database, use the method *GET* from ValueOperations class, like:


```java
valueOperation.get(<<key>>);
``` 


```java
ValueOperations<String, Transaction> valueOperation = redisTemplate.opsForValue();
Transaction tx = valueOperation.get(transactionId);
```


### Other articles of mine that you might like...

* [Redis - Instalación y Configuración](https://juanc4milo.dev/redis-instalacion-y-configuracion)
* [AWS S3 Batch Operations](https://juanc4milo.dev/aws-s3-batch-operations)
* [AWS S3 Inventory](https://juanc4milo.dev/inventario-aws-s3)
* [Qué ofrece y cómo se configura AWS Elasticache?](https://juanc4milo.dev/aws-elasticache)
* [Qué ofrece y cómo se configura Elasticache en AWS?](https://juanc4milo.dev/aws-elasticache)

**Do you like it?** You can [buy me a beer](https://buymeacoffee.com/juanc4milo) if you want.

> _Originally published at [juanc4milo.dev](https://juanc4milo.dev)_