Integrating Redis with Spring Boot: Dependencies, Configuration, and Usage Guide

This tutorial explains how to add Redis dependencies to a Spring Boot project, configure connection settings, use RedisTemplate for basic operations, enable Spring Cache, employ Redisson for distributed locks, and fine‑tune connection pool and timeout parameters, providing complete code examples.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Integrating Redis with Spring Boot: Dependencies, Configuration, and Usage Guide

Redis is a high‑performance key‑value store, and Spring Boot is a Java framework that simplifies development. Combining them allows easy use of Redis in Spring Boot projects for caching, session management, distributed locks, and other features.

1. Add Redis Dependency

Add the Redis starter dependency to pom.xml:

<dependencies>
  <!-- Spring Data Redis -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>
</dependencies>

2. Configure Redis Connection Information

Specify the Redis host and port in application.properties or application.yml:

spring.redis.host=127.0.0.1
spring.redis.port=6379

Adjust the values according to your Redis server.

3. Use RedisTemplate for Operations

1. Create RedisTemplate Bean

Define a RedisTemplate bean in a configuration class:

@Configuration
public class RedisConfig {

  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    return template;
  }
}

The example uses a JSON serializer for values; other serializers can be chosen as needed.

2. Inject RedisTemplate

Autowire the template in a service or controller:

@Autowired
private RedisTemplate<String, Object> redisTemplate;

3. Perform Redis Operations

Use the injected RedisTemplate to set and get values:

// Set a key‑value pair
redisTemplate.opsForValue().set("key", "value");

// Get the value
String value = (String) redisTemplate.opsForValue().get("key");

4. Use Spring Cache to Simplify Caching

1. Add Spring Cache Dependency

Add the cache starter to pom.xml (the same Redis starter is already included):

<dependencies>
  <!-- Spring Data Redis -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>

  <!-- Spring Cache -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>
</dependencies>

2. Enable Caching Support

Add @EnableCaching to the main application class:

@SpringBootApplication
@EnableCaching
public class Application {
  // ...
}

3. Use Cache Annotations

Apply Spring Cache annotations such as @Cacheable, @CachePut, and @CacheEvict on service methods:

@Service
public class DemoService {

  @Cacheable(value = "cacheName", key = "#id")
  public Object getData(String id) {
    // fetch from DB or other source
    return data;
  }

  @CachePut(value = "cacheName", key = "#id")
  public Object updateData(String id, Object newData) {
    // update DB or other source
    return newData;
  }

  @CacheEvict(value = "cacheName", key = "#id")
  public void deleteData(String id) {
    // delete from DB or other source
  }
}

5. Use Redisson to Implement Distributed Locks

1. Add Redisson Dependency

Add the Redisson starter to pom.xml:

<dependencies>
  <!-- Spring Data Redis -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>

  <!-- Redisson -->
  <dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.16.3</version>
  </dependency>
</dependencies>

2. Configure Redisson

Add a Redisson configuration entry, for example in application.properties:

# Single‑node Redisson configuration
spring.redis.redisson.config=classpath:redisson-single-node.yml

Define the connection details in redisson-single-node.yml.

3. Acquire a Distributed Lock with Redisson

Inject RedissonClient and use it to obtain a lock:

@Autowired
private RedissonClient redissonClient;

public void doSomething() {
  RLock lock = redissonClient.getLock("lockName");
  try {
    lock.lock();
    // critical section
  } finally {
    lock.unlock();
  }
}

6. Fine‑Tune Additional Redis Configurations

1. Connection Pool Settings

Redis can use a connection pool to improve performance. You can adjust pool parameters in redis.conf:

# Maximum number of connections
maxclients 10000

# TCP backlog length
tcp-backlog 511

# Max idle connections in the pool
maxidle 100

# Min idle connections in the pool
minidle 10

# Connection timeout (ms)
timeout 3000

# TCP keep‑alive
tcp-keepalive 0

Or configure the pool programmatically with JedisPoolConfig in Spring Boot:

@Configuration
public class RedisConfig {

  @Bean
  public JedisPoolConfig jedisPoolConfig() {
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    poolConfig.setMaxTotal(10000);
    poolConfig.setMaxIdle(100);
    poolConfig.setMinIdle(10);
    poolConfig.setMaxWaitMillis(3000);
    // other settings
    return poolConfig;
  }

  @Bean
  public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig poolConfig) {
    RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
    config.setHostName("127.0.0.1");
    config.setPort(6379);
    // other Redis settings

    JedisClientConfiguration clientConfig = JedisClientConfiguration.builder()
        .usePooling().poolConfig(poolConfig)
        .build();

    return new JedisConnectionFactory(config, clientConfig);
  }

  @Bean
  public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory connectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    return template;
  }
}

2. Timeout Settings

Set the Redis operation timeout to avoid long‑running blocks. In the Redis config file:

timeout 5000

Or configure it via JedisClientConfiguration in Spring:

@Bean
public JedisClientConfiguration jedisClientConfiguration() {
  Duration timeout = Duration.ofSeconds(5);
  return JedisClientConfiguration.builder()
      .readTimeout(timeout)
      .build();
}

@Bean
public JedisConnectionFactory jedisConnectionFactory(JedisClientConfiguration clientConfig) {
  // other configuration
  return new JedisConnectionFactory(config, clientConfig);
}

Backend Technical Community Invitation

Backend‑specific technical group

Build a high‑quality technical exchange community. Developers, technical recruiters, and anyone willing to share job referrals are welcome to join, help each other, and grow together.

Communicate responsibly, focusing on technical discussion , job referrals , and industry exploration .

Advertisements are prohibited; do not trust private messages to avoid scams.

Contact me to be added to the group.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentredisSpring Bootdistributed-lockredisson
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.