【Java后端】 Spring Boot 集成 Redis 全攻略

Spring Boot 集成 Redis 全攻略

一、前言

在现代应用中,缓存 几乎是性能优化的必备手段。Redis 作为高性能的内存数据库,不仅支持键值对缓存,还支持丰富的数据结构(如 List、Set、Hash、ZSet 等),被广泛用于缓存、分布式锁、消息队列、计数器等场景。

Spring Boot 提供了开箱即用的 Redis 集成支持,开发者可以非常方便地在项目中使用 Redis。


二、环境准备

1. 启动 Redis 服务

如果本地已安装 Redis,直接启动即可;推荐使用 Docker 快速部署:

bash 复制代码
docker run -d --name redis -p 6379:6379 redis:6.2

2. 添加依赖

pom.xml 中引入 Redis 相关依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

三、配置 Redis

application.yml 中配置 Redis 连接信息:

yaml 复制代码
spring:
  redis:
    host: localhost
    port: 6379
    password:   # 如果设置了密码,写在这里
    database: 0
    timeout: 2000ms
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms

Spring Boot 默认使用 Lettuce 作为 Redis 客户端,比 Jedis 更加高效、支持异步和响应式编程。


四、基本使用

1. 使用 StringRedisTemplate

适合存储字符串类型数据:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/set")
    public String setValue(@RequestParam String key, @RequestParam String value) {
        stringRedisTemplate.opsForValue().set(key, value);
        return "成功设置: " + key + " -> " + value;
    }

    @GetMapping("/get")
    public String getValue(@RequestParam String key) {
        return "查询结果: " + stringRedisTemplate.opsForValue().get(key);
    }
}

访问示例:

复制代码
http://localhost:8080/redis/set?key=name&value=Tom
http://localhost:8080/redis/get?key=name

2. 使用 RedisTemplate

支持对象序列化存储,需要配置 RedisTemplate 的序列化方式:

java 复制代码
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 使用 Jackson 序列化
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
                new Jackson2JsonRedisSerializer<>(Object.class);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // key 使用 String 序列化
        template.setKeySerializer(new StringRedisSerializer());
        // value 使用 JSON 序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();
        return template;
    }
}

使用示例:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/save")
    public String saveUser(@RequestBody User user) {
        redisTemplate.opsForValue().set("user:" + user.getId(), user);
        return "保存成功: " + user.getName();
    }

    @GetMapping("/get/{id}")
    public Object getUser(@PathVariable String id) {
        return redisTemplate.opsForValue().get("user:" + id);
    }
}

五、整合 Spring Cache

Spring Boot 提供了注解式缓存,只需加上注解即可使用 Redis 缓存。

1. 开启缓存功能

在主类上加上 @EnableCaching

java 复制代码
@SpringBootApplication
@EnableCaching
public class RedisApplication {
    public static void main(String[] args) {
        SpringApplication.run(RedisApplication.class, args);
    }
}

2. 使用缓存注解

  • @Cacheable:先查缓存,没有则执行方法并放入缓存
  • @CachePut:更新缓存
  • @CacheEvict:清除缓存

示例:

java 复制代码
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    @Cacheable(value = "product", key = "#id")
    public String getProductById(Long id) {
        System.out.println("执行了数据库查询...");
        return "商品-" + id;
    }
}

调用两次 getProductById(1L),只有第一次会执行数据库查询,第二次直接走缓存。


六、Redis 的常见应用场景

  1. 缓存热点数据

    • 用户信息、商品信息、配置信息等。
  2. 分布式锁

    • 通过 SETNX + EXPIRE 实现。
  3. 计数器

    • 访问量统计、点赞数、库存扣减等。
  4. 消息队列

    • 使用 ListStream 实现简单队列。

七、常见问题与优化

  1. 缓存穿透:查询的数据不存在,每次都打到数据库。

    • 解决:缓存空对象,布隆过滤器。
  2. 缓存击穿:某个热点 Key 失效,大量请求同时打到数据库。

    • 解决:设置互斥锁、热点数据永不过期。
  3. 缓存雪崩:大量 Key 在同一时间失效,导致数据库被打爆。

    • 解决:过期时间加随机数,分散失效时间。

八、总结

本文介绍了 Spring Boot 集成 Redis 的完整流程,从环境搭建、依赖引入、基础操作,到与 Spring Cache 注解的整合,并补充了 Redis 在实际业务中的应用场景与常见问题。

合理利用 Redis,不仅能显著提升系统性能,还能在高并发场景下保障服务稳定性。