You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 8.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. ## spring-boot-demo-cache-redis
  2. > 此 demo 主要演示了 Spring Boot 如何整合 redis,操作redis中的数据,并使用redis缓存数据。连接池使用 Lettuce。
  3. ## 1.开发步骤
  4. ### 1.1.添加依赖
  5. ```xml
  6. <dependencies>
  7. <dependency>
  8. <groupId>com.xkcoding</groupId>
  9. <artifactId>common-tools</artifactId>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.xkcoding</groupId>
  13. <artifactId>demo-cache-api</artifactId>
  14. <version>1.0.0-SNAPSHOT</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-web</artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-data-redis</artifactId>
  23. </dependency>
  24. <!-- 对象池,如果存在该依赖会自动注入 -->
  25. <!-- https://docs.spring.io/spring-boot/docs/3.0.0-M4/reference/htmlsingle/#data.nosql.redis.connecting -->
  26. <dependency>
  27. <groupId>org.apache.commons</groupId>
  28. <artifactId>commons-pool2</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-test</artifactId>
  33. <scope>test</scope>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.projectlombok</groupId>
  37. <artifactId>lombok</artifactId>
  38. <optional>true</optional>
  39. </dependency>
  40. </dependencies>
  41. ```
  42. ### 1.2.配置文件
  43. ```yaml
  44. spring:
  45. redis:
  46. host: localhost
  47. # 连接超时时间(记得添加单位,Duration)
  48. timeout: 10000ms
  49. # Redis默认情况下有16个分片,这里配置具体使用的分片
  50. # database: 0
  51. lettuce:
  52. pool:
  53. # 连接池最大连接数(使用负值表示没有限制) 默认 8
  54. max-active: 8
  55. # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
  56. max-wait: -1ms
  57. # 连接池中的最大空闲连接 默认 8
  58. max-idle: 8
  59. # 连接池中的最小空闲连接 默认 0
  60. min-idle: 0
  61. cache:
  62. # 一般来说是不用配置的,Spring Cache 会根据依赖的包自行装配
  63. type: redis
  64. logging:
  65. level:
  66. com.xkcoding: debug
  67. ```
  68. ### 1.3.自动装配Redis缓存管理
  69. ```java
  70. @EnableCaching
  71. @Configuration
  72. @AutoConfigureAfter(RedisAutoConfiguration.class)
  73. public class RedisCacheAutoConfiguration {
  74. /**
  75. * 默认情况下的模板只能支持RedisTemplate<String, String>,也就是只能存入字符串,因此支持序列化
  76. */
  77. @Bean
  78. public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
  79. RedisTemplate<String, Serializable> template = new RedisTemplate<>();
  80. template.setKeySerializer(new StringRedisSerializer());
  81. template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  82. template.setConnectionFactory(redisConnectionFactory);
  83. return template;
  84. }
  85. /**
  86. * 配置使用注解的时候缓存配置,默认是序列化反序列化的形式,加上此配置则为 json 形式
  87. */
  88. @Bean
  89. public CacheManager cacheManager(RedisConnectionFactory factory) {
  90. // 配置序列化
  91. RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
  92. RedisCacheConfiguration redisCacheConfiguration =
  93. config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
  94. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
  95. return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();
  96. }
  97. }
  98. ```
  99. ### 1.4.缓存通过注解实现
  100. > 为了减少重复代码,该部分我将其抽取实现在 demo-cache-api 模块中
  101. ```java
  102. @Slf4j
  103. @Service
  104. public class UserService {
  105. /**
  106. * 模拟数据库
  107. */
  108. private static final Map<Long, User> DATABASES = new HashMap<>() {{
  109. put(1L, new User(1L, "user1"));
  110. put(2L, new User(2L, "user2"));
  111. put(3L, new User(3L, "user3"));
  112. }};
  113. /**
  114. * 保存或修改用户
  115. *
  116. * @param user 用户对象
  117. * @return 操作结果
  118. */
  119. @CachePut(value = "user", key = "#user.id")
  120. public User saveOrUpdate(User user) {
  121. DATABASES.put(user.getId(), user);
  122. log.info("保存用户【user】= {}", user);
  123. return user;
  124. }
  125. /**
  126. * 获取用户
  127. *
  128. * @param id key值
  129. * @return 返回结果
  130. */
  131. @Cacheable(value = "user", key = "#id")
  132. public User get(Long id) {
  133. // 我们假设从数据库读取
  134. log.info("查询用户【id】= {}", id);
  135. return DATABASES.get(id);
  136. }
  137. /**
  138. * 删除
  139. *
  140. * @param id key值
  141. */
  142. @CacheEvict(value = "user", key = "#id")
  143. public void delete(Long id) {
  144. DATABASES.remove(id);
  145. log.info("删除用户【id】= {}", id);
  146. }
  147. }
  148. ```
  149. ## 2.测试
  150. ### 2.1.环境搭建
  151. 主要是 redis 环境的搭建,这里我提供了 docker-compose 文件,方便同学们一键启动测试环境
  152. ```bash
  153. $ cd demo-cache/demo-cache-redis
  154. $ docker compose -f docker-compose.env.yml up
  155. ```
  156. ### 2.2.测试 Redis 基础功能
  157. > 主要测试使用 `RedisTemplate` 操作 `Redis` 中的数据,查看是否正常序列化:
  158. >
  159. > - opsForValue:对应 String(字符串)
  160. > - opsForZSet:对应 ZSet(有序集合)
  161. > - opsForHash:对应 Hash(哈希)
  162. > - opsForList:对应 List(列表)
  163. > - opsForSet:对应 Set(集合)
  164. > - opsForGeo:** 对应 GEO(地理位置)
  165. ```java
  166. @Slf4j
  167. @SpringBootTest
  168. public class RedisTest {
  169. @Autowired
  170. private StringRedisTemplate stringRedisTemplate;
  171. @Autowired
  172. private RedisTemplate<String, Serializable> redisCacheTemplate;
  173. /**
  174. * 测试 Redis 操作
  175. */
  176. @Test
  177. public void get() throws InterruptedException {
  178. // 测试线程安全,程序结束查看redis中count的值是否为1000
  179. ExecutorService executorService = Executors.newFixedThreadPool(1000);
  180. CountDownLatch wait = new CountDownLatch(1000);
  181. IntStream.range(0, 1000).forEach(i -> executorService.execute(() -> {
  182. stringRedisTemplate.opsForValue().increment("count", 1);
  183. wait.countDown();
  184. }));
  185. wait.await();
  186. log.debug("【count】= {}", stringRedisTemplate.opsForValue().getAndExpire("count", Duration.ofSeconds(10)));
  187. stringRedisTemplate.opsForValue().set("k1", "v1");
  188. String k1 = stringRedisTemplate.opsForValue().getAndExpire("k1", Duration.ofSeconds(10));
  189. log.debug("【k1】= {}", k1);
  190. // 以下演示整合,具体Redis命令可以参考官方文档
  191. String key = "xkcoding:user:1";
  192. redisCacheTemplate.opsForValue().set(key, new User(1L, "user1"));
  193. // 对应 String(字符串)
  194. User user = (User) redisCacheTemplate.opsForValue().get(key);
  195. String userSerialized = stringRedisTemplate.opsForValue().getAndExpire(key, Duration.ofSeconds(10));
  196. log.debug("【user】= {}", user);
  197. log.debug("【userSerialized】= {}", userSerialized);
  198. }
  199. }
  200. ```
  201. ### 2.3.测试Redis缓存是否生效
  202. ```java
  203. @Slf4j
  204. @SpringBootTest
  205. public class UserServiceTest {
  206. @Autowired
  207. private UserService userService;
  208. /**
  209. * 获取两次,查看日志验证缓存
  210. */
  211. @Test
  212. public void getTwice() {
  213. // 模拟查询id为1的用户
  214. User user1 = userService.get(1L);
  215. log.debug("【user1】= {}", user1);
  216. // 再次查询
  217. User user2 = userService.get(1L);
  218. log.debug("【user2】= {}", user2);
  219. // 查看日志,只打印一次日志,证明缓存生效
  220. }
  221. /**
  222. * 先存,再查询,查看日志验证缓存
  223. */
  224. @Test
  225. public void getAfterSave() {
  226. userService.saveOrUpdate(new User(4L, "测试中文"));
  227. User user = userService.get(4L);
  228. log.debug("【user】= {}", user);
  229. // 查看日志,只打印保存用户的日志,查询是未触发查询日志,因此缓存生效
  230. }
  231. /**
  232. * 测试删除,查看redis是否存在缓存数据
  233. */
  234. @Test
  235. public void deleteUser() {
  236. // 查询一次,使redis中存在缓存数据
  237. userService.get(1L);
  238. // 删除,查看redis是否存在缓存数据
  239. userService.delete(1L);
  240. }
  241. }
  242. ```
  243. ## 3.参考
  244. - [Spring Boot 官方文档之连接 Redis](https://docs.spring.io/spring-boot/docs/3.0.0-M4/reference/htmlsingle/#data.nosql.redis)
  245. - [Spring Boot 官方文档之 Redis 缓存](https://docs.spring.io/spring-boot/docs/3.0.0-M4/reference/htmlsingle/#io.caching.provider.redis)
  246. - [spring-data-redis 官方文档](https://docs.spring.io/spring-data/redis/docs/3.0.0-M5/reference/html/)
  247. - [Redis 官方文档](https://redis.io/docs/)