当前位置: 首页 > news >正文

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

Spring Boot 集成 Redis 全攻略

一、前言

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

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


二、环境准备

1. 启动 Redis 服务

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

docker run -d --name redis -p 6379:6379 redis:6.2

2. 添加依赖

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

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

三、配置 Redis

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

spring:redis:host: localhostport: 6379password:   # 如果设置了密码,写在这里database: 0timeout: 2000mslettuce:pool:max-active: 8max-idle: 8min-idle: 0max-wait: -1ms

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


四、基本使用

1. 使用 StringRedisTemplate

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

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 {@Autowiredprivate 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 的序列化方式:

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 {@Beanpublic 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;}
}

使用示例:

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 {@Autowiredprivate 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

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

2. 使用缓存注解

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

示例:

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,不仅能显著提升系统性能,还能在高并发场景下保障服务稳定性。

http://www.dtcms.com/a/344238.html

相关文章:

  • java视频播放网站
  • 正点原子【第四期】Linux之驱动开发学习笔记-2.1LED灯驱动实验(直接操作寄存器)
  • 分布式与微服务
  • 20250822在Ubuntu24.04.2下指定以太网卡的IP地址
  • 深度学习入门详解:从神经网络到实践应用
  • 【English】复合句中的先行词在从句中是否充当成分
  • 吉利汽车与芯鼎微成立联合创新实验室共谱车规级LCoS显示新篇章
  • 面向RF设计人员的微带贴片天线计算器
  • Gamma校正硬件设计实现
  • Elasticsearch搜索原理
  • 加密狗如何抵御各类破解与攻击?深度解析加密狗多层保护机制
  • 关于数据产业规模测算的认识与思考
  • Paddle3D-PETRv1 精度测试与推理实践指南
  • JavaSSM框架从入门到精通!第三天(MyBatis(二))!
  • C++ OpenGL中几个常见库及其区别
  • 轮廓检测技术不仅能精确计算图像中的轮廓数量,还能完整记录每个轮廓包含的所有像素点坐标
  • Linux服务测试
  • Jenkins用户授权管理 企业级jenkins授权策略 jenkins用户权限分配
  • Flutter InheritedWidget 详解
  • 学习嵌入式的第二十四天——数据结构——队列和树
  • Flutter 从入门到精通 - 完整课程总结
  • 打印机怎么连接电脑?打印机驱动?【图文详解】USB连接打印机?wifi连接打印机?
  • ZKmall模块商城的跨境电商支付安全方案:加密与权限的双重防护
  • STL关联式容器解析:map与set详解
  • 电脑芯片大的32位与64位指的是什么
  • 94. 城市间货物运输 I, Bellman_ford 算法
  • 解读商业智能BI,数据仓库中的元数据
  • Python训练营打卡Day40-简单CNN
  • memcmp 函数的使用及其模拟实现
  • io.github.lucksiege:pictureselector状态栏没沉浸问题