Databases 14 min read

How to Install, Integrate, and Use Redis with Spring Boot

This article introduces Redis, explains how to install it on various platforms, demonstrates integrating Redis with Spring Boot using Spring Cache annotations, configures connection pools for Lettuce and Jedis, and provides custom Redis service implementations for flexible cache operations.

IT Services Circle
IT Services Circle
IT Services Circle
How to Install, Integrate, and Use Redis with Spring Boot

Redis is a high‑performance in‑memory key‑value store written in C, widely used by many internet companies such as Alibaba, Tencent, GitHub and Stack Overflow.

Installation : The official website provides packages for Linux, macOS and Windows. On macOS you can simply run brew install redis and start the server with redis-server . In production you typically install Redis on a Linux server, e.g., via a control panel.

Integration with Spring Boot : Use Spring Cache annotations ( @EnableCaching , @Cacheable , @CachePut , @CacheEvict ) to let Spring manage Redis caching automatically.

Step 1 – Add dependency :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Step 2 – Configure connection (application.yml):

spring:
    redis:
        host: 118.xx.xx.xxx # Redis server address
        database: 0          # DB index, default 0
        port: 6379           # Port
        password: xx         # Password, empty if none
        timeout: 1000ms      # Connection timeout

Step 3 – RedisConfig (set JSON serializer for RedisTemplate ):

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate
redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate
redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        RedisSerializer
serializer = redisSerializer();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(serializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    @Bean
    public RedisSerializer
redisSerializer() {
        Jackson2JsonRedisSerializer
serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
        serializer.setObjectMapper(objectMapper);
        return serializer;
    }
}

Cache expiration (RedisCacheManager bean):

@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer()))
            .entryTtl(Duration.ofDays(1));
    return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}

Connection pool configuration :

For Lettuce (Spring Boot 2.x default) add pool settings and the commons-pool2 dependency:

spring:
    redis:
        lettuce:
            pool:
                max-active: 8 # max connections
                max-idle: 8   # max idle
                min-idle: 0   # min idle
                max-wait: -1ms # no limit
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.6.2</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>

For Jedis (alternative client) exclude Lettuce and add Jedis dependency, then configure its pool:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
spring:
    redis:
        jedis:
            pool:
                max-active: 8
                max-idle: 8
                min-idle: 0
                max-wait: -1ms

Custom RedisService interface for direct operations:

public interface RedisService {
    /** Save a value */
    void set(String key, Object value);
    /** Get a value */
    Object get(String key);
    /** Delete a value */
    Boolean del(String key);
    // ... other methods
}

Implementation:

@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private RedisTemplate
redisTemplate;
    @Override
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }
    @Override
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }
    @Override
    public Boolean del(String key) {
        return redisTemplate.delete(key);
    }
    // ... more methods
}

Test endpoint in PostTagController that updates a tag, stores it in Redis, and reads it back:

@Controller
@Api(tags = "标签")
@RequestMapping("/postTag")
public class PostTagController {
    @Autowired private IPostTagService postTagService;
    @Autowired private IPostTagRelationService postTagRelationService;
    @Autowired private RedisService redisService;

    @RequestMapping(value = "/simpleTest", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("修改标签/Redis 测试用")
    public ResultObject
simpleTest(@Valid PostTagParam postAddTagParam) {
        if (postAddTagParam.getPostTagId() == null) {
            return ResultObject.failed("标签id不能为空");
        }
        PostTag postTag = postTagService.getById(postAddTagParam.getPostTagId());
        if (postTag == null) {
            return ResultObject.failed("标签不存在");
        }
        QueryWrapper
queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("description", postAddTagParam.getDescription());
        int count = postTagService.count(queryWrapper);
        if (count > 0) {
            return ResultObject.failed("标签名称已存在");
        }
        BeanUtils.copyProperties(postAddTagParam, postTag);
        boolean successFlag = postTagService.updateById(postTag);
        String key = "redis:simple:" + postTag.getPostTagId();
        redisService.set(key, postTag);
        PostTag cachePostTag = (PostTag) redisService.get(key);
        return ResultObject.success(cachePostTag);
    }
}

After restarting the application, the endpoint can be tested with Knife4j, and the stored data can be verified using a Redis client such as Red.

Conclusion : Redis provides powerful in‑memory caching; combined with Spring Cache and a custom service layer you gain both simplicity and fine‑grained control over cached data.

JavaDatabaseRediscachingSpring BootSpring Cache
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login 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.