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 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. # spring-boot-demo-cache-redis
  2. > 此 demo 主要演示了 Spring Boot 如何整合 redis,操作redis中的数据,并使用redis缓存数据。连接池使用 Lettuce。
  3. ## pom.xml
  4. ```xml
  5. <?xml version="1.0" encoding="UTF-8"?>
  6. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  7. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  8. <modelVersion>4.0.0</modelVersion>
  9. <artifactId>spring-boot-demo-cache-redis</artifactId>
  10. <version>1.0.0-SNAPSHOT</version>
  11. <packaging>jar</packaging>
  12. <name>spring-boot-demo-cache-redis</name>
  13. <description>Demo project for Spring Boot</description>
  14. <parent>
  15. <groupId>com.xkcoding</groupId>
  16. <artifactId>spring-boot-demo</artifactId>
  17. <version>1.0.0-SNAPSHOT</version>
  18. </parent>
  19. <properties>
  20. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  21. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  22. <java.version>1.8</java.version>
  23. </properties>
  24. <dependencies>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-data-redis</artifactId>
  32. </dependency>
  33. <!-- 对象池,使用redis时必须引入 -->
  34. <dependency>
  35. <groupId>org.apache.commons</groupId>
  36. <artifactId>commons-pool2</artifactId>
  37. </dependency>
  38. <!-- 引入 jackson 对象json转换 -->
  39. <dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-json</artifactId>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-starter-test</artifactId>
  46. <scope>test</scope>
  47. </dependency>
  48. <dependency>
  49. <groupId>com.google.guava</groupId>
  50. <artifactId>guava</artifactId>
  51. </dependency>
  52. <dependency>
  53. <groupId>cn.hutool</groupId>
  54. <artifactId>hutool-all</artifactId>
  55. </dependency>
  56. <dependency>
  57. <groupId>org.projectlombok</groupId>
  58. <artifactId>lombok</artifactId>
  59. <optional>true</optional>
  60. </dependency>
  61. </dependencies>
  62. <build>
  63. <finalName>spring-boot-demo-cache-redis</finalName>
  64. <plugins>
  65. <plugin>
  66. <groupId>org.springframework.boot</groupId>
  67. <artifactId>spring-boot-maven-plugin</artifactId>
  68. </plugin>
  69. </plugins>
  70. </build>
  71. </project>
  72. ```
  73. ## application.yml
  74. ```yaml
  75. spring:
  76. redis:
  77. host: localhost
  78. # 连接超时时间(记得添加单位,Duration)
  79. timeout: 10000ms
  80. # Redis默认情况下有16个分片,这里配置具体使用的分片
  81. # database: 0
  82. lettuce:
  83. pool:
  84. # 连接池最大连接数(使用负值表示没有限制) 默认 8
  85. max-active: 8
  86. # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
  87. max-wait: -1ms
  88. # 连接池中的最大空闲连接 默认 8
  89. max-idle: 8
  90. # 连接池中的最小空闲连接 默认 0
  91. min-idle: 0
  92. cache:
  93. # 一般来说是不用配置的,Spring Cache 会根据依赖的包自行装配
  94. type: redis
  95. logging:
  96. level:
  97. com.xkcoding: debug
  98. ```
  99. ## RedisConfig.java
  100. ```java
  101. /**
  102. * <p>
  103. * redis配置
  104. * </p>
  105. *
  106. * @package: com.xkcoding.cache.redis.config
  107. * @description: redis配置
  108. * @author: yangkai.shen
  109. * @date: Created in 2018/11/15 16:41
  110. * @copyright: Copyright (c) 2018
  111. * @version: V1.0
  112. * @modified: yangkai.shen
  113. */
  114. @Configuration
  115. @AutoConfigureAfter(RedisAutoConfiguration.class)
  116. @EnableCaching
  117. public class RedisConfig {
  118. /**
  119. * 默认情况下的模板只能支持RedisTemplate<String, String>,也就是只能存入字符串,因此支持序列化
  120. */
  121. @Bean
  122. public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
  123. RedisTemplate<String, Serializable> template = new RedisTemplate<>();
  124. template.setKeySerializer(new StringRedisSerializer());
  125. template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  126. template.setConnectionFactory(redisConnectionFactory);
  127. return template;
  128. }
  129. /**
  130. * 配置使用注解的时候缓存配置,默认是序列化反序列化的形式,加上此配置则为 json 形式
  131. */
  132. @Bean
  133. public CacheManager cacheManager(RedisConnectionFactory factory) {
  134. // 配置序列化
  135. RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
  136. RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
  137. return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();
  138. }
  139. }
  140. ```
  141. ## UserServiceImpl.java
  142. ```java
  143. /**
  144. * <p>
  145. * UserService
  146. * </p>
  147. *
  148. * @package: com.xkcoding.cache.redis.service.impl
  149. * @description: UserService
  150. * @author: yangkai.shen
  151. * @date: Created in 2018/11/15 16:45
  152. * @copyright: Copyright (c) 2018
  153. * @version: V1.0
  154. * @modified: yangkai.shen
  155. */
  156. @Service
  157. @Slf4j
  158. public class UserServiceImpl implements UserService {
  159. /**
  160. * 模拟数据库
  161. */
  162. private static final Map<Long, User> DATABASES = Maps.newConcurrentMap();
  163. /**
  164. * 初始化数据
  165. */
  166. static {
  167. DATABASES.put(1L, new User(1L, "user1"));
  168. DATABASES.put(2L, new User(2L, "user2"));
  169. DATABASES.put(3L, new User(3L, "user3"));
  170. }
  171. /**
  172. * 保存或修改用户
  173. *
  174. * @param user 用户对象
  175. * @return 操作结果
  176. */
  177. @CachePut(value = "user", key = "#user.id")
  178. @Override
  179. public User saveOrUpdate(User user) {
  180. DATABASES.put(user.getId(), user);
  181. log.info("保存用户【user】= {}", user);
  182. return user;
  183. }
  184. /**
  185. * 获取用户
  186. *
  187. * @param id key值
  188. * @return 返回结果
  189. */
  190. @Cacheable(value = "user", key = "#id")
  191. @Override
  192. public User get(Long id) {
  193. // 我们假设从数据库读取
  194. log.info("查询用户【id】= {}", id);
  195. return DATABASES.get(id);
  196. }
  197. /**
  198. * 删除
  199. *
  200. * @param id key值
  201. */
  202. @CacheEvict(value = "user", key = "#id")
  203. @Override
  204. public void delete(Long id) {
  205. DATABASES.remove(id);
  206. log.info("删除用户【id】= {}", id);
  207. }
  208. }
  209. ```
  210. ## RedisTest.java
  211. > 主要测试使用 `RedisTemplate` 操作 `Redis` 中的数据:
  212. >
  213. > - opsForValue:对应 String(字符串)
  214. > - opsForZSet:对应 ZSet(有序集合)
  215. > - opsForHash:对应 Hash(哈希)
  216. > - opsForList:对应 List(列表)
  217. > - opsForSet:对应 Set(集合)
  218. > - opsForGeo:** 对应 GEO(地理位置)
  219. ```java
  220. /**
  221. * <p>
  222. * Redis测试
  223. * </p>
  224. *
  225. * @package: com.xkcoding.cache.redis
  226. * @description: Redis测试
  227. * @author: yangkai.shen
  228. * @date: Created in 2018/11/15 17:17
  229. * @copyright: Copyright (c) 2018
  230. * @version: V1.0
  231. * @modified: yangkai.shen
  232. */
  233. @Slf4j
  234. public class RedisTest extends SpringBootDemoCacheRedisApplicationTests {
  235. @Autowired
  236. private StringRedisTemplate stringRedisTemplate;
  237. @Autowired
  238. private RedisTemplate<String, Serializable> redisCacheTemplate;
  239. /**
  240. * 测试 Redis 操作
  241. */
  242. @Test
  243. public void get() {
  244. // 测试线程安全,程序结束查看redis中count的值是否为1000
  245. ExecutorService executorService = Executors.newFixedThreadPool(1000);
  246. IntStream.range(0, 1000).forEach(i -> executorService.execute(() -> stringRedisTemplate.opsForValue().increment("count", 1)));
  247. stringRedisTemplate.opsForValue().set("k1", "v1");
  248. String k1 = stringRedisTemplate.opsForValue().get("k1");
  249. log.debug("【k1】= {}", k1);
  250. // 以下演示整合,具体Redis命令可以参考官方文档
  251. String key = "xkcoding:user:1";
  252. redisCacheTemplate.opsForValue().set(key, new User(1L, "user1"));
  253. // 对应 String(字符串)
  254. User user = (User) redisCacheTemplate.opsForValue().get(key);
  255. log.debug("【user】= {}", user);
  256. }
  257. }
  258. ```
  259. ## UserServiceTest.java
  260. > 主要测试使用Redis缓存是否起效
  261. ```java
  262. /**
  263. * <p>
  264. * Redis - 缓存测试
  265. * </p>
  266. *
  267. * @package: com.xkcoding.cache.redis.service
  268. * @description: Redis - 缓存测试
  269. * @author: yangkai.shen
  270. * @date: Created in 2018/11/15 16:53
  271. * @copyright: Copyright (c) 2018
  272. * @version: V1.0
  273. * @modified: yangkai.shen
  274. */
  275. @Slf4j
  276. public class UserServiceTest extends SpringBootDemoCacheRedisApplicationTests {
  277. @Autowired
  278. private UserService userService;
  279. /**
  280. * 获取两次,查看日志验证缓存
  281. */
  282. @Test
  283. public void getTwice() {
  284. // 模拟查询id为1的用户
  285. User user1 = userService.get(1L);
  286. log.debug("【user1】= {}", user1);
  287. // 再次查询
  288. User user2 = userService.get(1L);
  289. log.debug("【user2】= {}", user2);
  290. // 查看日志,只打印一次日志,证明缓存生效
  291. }
  292. /**
  293. * 先存,再查询,查看日志验证缓存
  294. */
  295. @Test
  296. public void getAfterSave() {
  297. userService.saveOrUpdate(new User(4L, "测试中文"));
  298. User user = userService.get(4L);
  299. log.debug("【user】= {}", user);
  300. // 查看日志,只打印保存用户的日志,查询是未触发查询日志,因此缓存生效
  301. }
  302. /**
  303. * 测试删除,查看redis是否存在缓存数据
  304. */
  305. @Test
  306. public void deleteUser() {
  307. // 查询一次,使redis中存在缓存数据
  308. userService.get(1L);
  309. // 删除,查看redis是否存在缓存数据
  310. userService.delete(1L);
  311. }
  312. }
  313. ```
  314. ## 参考
  315. - spring-data-redis 官方文档:https://docs.spring.io/spring-data/redis/docs/2.0.1.RELEASE/reference/html/
  316. - redis 文档:https://redis.io/documentation
  317. - redis 中文文档:http://www.redis.cn/commands.html

一个用来深度学习并实战 spring boot 的项目,目前总共包含 66 个集成demo,已经完成 55 个。