SpringBoot + Redis

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.apache.commons</groupId>
  7. <artifactId>commons-pool2</artifactId>
  8. </dependency>
  1. spring:
  2. redis:
  3. host: localhost
  4. database: 0
  5. port: 6379
  6. password: redis
  7. lettuce:
  8. pool:
  9. max-active: 8 # 连接池最大连接数(使用负值表示没有限制) 默认 8
  10. max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
  11. max-idle: 8 # 连接池中的最大空闲连接 默认 8
  12. min-idle: 0 # 连接池中的最小空闲连接 默认 0
  1. @Configuration
  2. @EnableCaching
  3. public class RedisConfig extends CachingConfigurerSupport {
  4. @Bean
  5. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  6. RedisTemplate<String, Object> template = new RedisTemplate<>();
  7. // 配置连接工厂
  8. template.setConnectionFactory(factory);
  9. //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
  10. Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
  11. ObjectMapper om = new ObjectMapper();
  12. // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
  13. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  14. jacksonSeial.setObjectMapper(om);
  15. // 值采用json序列化
  16. template.setValueSerializer(jacksonSeial);
  17. //使用StringRedisSerializer来序列化和反序列化redis的key值
  18. template.setKeySerializer(new StringRedisSerializer());
  19. // 设置hash key 和value序列化模式
  20. template.setHashKeySerializer(new StringRedisSerializer());
  21. template.setHashValueSerializer(jacksonSeial);
  22. template.afterPropertiesSet();
  23. return template;
  24. }
  25. }
  1. @Data
  2. @NoArgsConstructor
  3. public class User implements Serializable {
  4. private int age;
  5. private String name;
  6. @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
  7. private Date data;
  8. public User(int age, String name,Date date) {
  9. this.age = age;
  10. this.name = name;
  11. this.data = date;
  12. }
  13. }
  1. @Resource
  2. private RedisUtil redisUtil;
  3. private String key = "testKey";
  4. private String userKey = "testKey";
  5. @Test
  6. void redisSetUser() throws JsonProcessingException {
  7. ObjectMapper mapper=new ObjectMapper();//定义一个转化对象
  8. User user =new User(10,"zhangsan",new Date());
  9. redisUtil.set(userKey, mapper.writeValueAsString(user));
  10. }
  11. @Test
  12. void redisGetUser() throws JsonProcessingException {
  13. ObjectMapper mapper=new ObjectMapper();//定义一个转化对象
  14. String s = redisUtil.get(userKey).toString();
  15. User user = mapper.readValue(s, User.class);
  16. System.out.println(user.getAge());
  17. System.out.println(user.getName());
  18. System.out.println(user.getData());
  19. }
  20. @Test
  21. void redisget(){
  22. System.out.println(redisUtil.get(key));
  23. }
  24. @Test
  25. void redisSet1() {
  26. redisUtil.set(key,"value");
  27. }
  1. @Component
  2. public class RedisUtil {
  3. @Autowired
  4. private RedisTemplate<String, Object> redisTemplate;
  5. // 时间单位 默认秒 timeUnit
  6. public static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
  7. public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
  8. this.redisTemplate = redisTemplate;
  9. }
  10. // 基础 ----------------------- start --------------------------
  11. /**
  12. * 指定缓存失效时间
  13. * @param key 键
  14. * @param time 时间(秒)
  15. * @return true / false
  16. */
  17. public boolean expire(String key, long time) {
  18. try {
  19. if (time > 0) {
  20. redisTemplate.expire(key, time, TIME_UNIT);
  21. }
  22. return true;
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. return false;
  26. }
  27. }
  28. /**
  29. * 根据 key 获取过期时间
  30. * @param key 键
  31. * @return
  32. */
  33. public long getExpire(String key) {
  34. return redisTemplate.getExpire(key, TIME_UNIT);
  35. }
  36. /**
  37. * 判断 key 是否存在
  38. * @param key 键
  39. * @return true / false
  40. */
  41. public boolean hasKey(String key) {
  42. try {
  43. return redisTemplate.hasKey(key);
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. return false;
  47. }
  48. }
  49. /**
  50. * 删除缓存
  51. * @param key 键(一个或者多个)
  52. */
  53. public void del(String... key) {
  54. if (key != null && key.length > 0) {
  55. if (key.length == 1) {
  56. redisTemplate.delete(key[0]);
  57. } else {
  58. // 传入一个 Collection<String> 集合
  59. List keys = CollectionUtils.arrayToList(key);
  60. redisTemplate.delete(keys);
  61. }
  62. }
  63. }
  64. // 基础 ----------------------- end --------------------------
  65. // String ----------------------- start --------------------------
  66. /**
  67. * 普通缓存获取
  68. * @param key 键
  69. * @return 值
  70. */
  71. public Object get(String key) {
  72. return key == null ? null : redisTemplate.opsForValue().get(key);
  73. }
  74. /**
  75. * 普通缓存放入
  76. * @param key 键
  77. * @param value 值
  78. * @return true / false
  79. */
  80. public boolean set(String key, Object value) {
  81. try {
  82. redisTemplate.opsForValue().set(key, value);
  83. return true;
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. return false;
  87. }
  88. }
  89. /**
  90. * 普通缓存放入并设置时间
  91. * @param key 键
  92. * @param value 值
  93. * @param time 时间(秒),如果 time < 0 则设置无限时间
  94. * @return true / false
  95. */
  96. public boolean set(String key, Object value, long time) {
  97. try {
  98. if (time > 0) {
  99. redisTemplate.opsForValue().set(key, value, time, TIME_UNIT);
  100. } else {
  101. set(key, value);
  102. }
  103. return true;
  104. } catch (Exception e) {
  105. e.printStackTrace();
  106. return false;
  107. }
  108. }
  109. /**
  110. * 递增
  111. * @param key 键
  112. * @param delta 递增大小
  113. * @return
  114. */
  115. public long incr(String key, long delta) {
  116. if (delta < 0) {
  117. throw new RuntimeException("递增因子必须大于 0");
  118. }
  119. return redisTemplate.opsForValue().increment(key, delta);
  120. }
  121. /**
  122. * 递减
  123. * @param key 键
  124. * @param delta 递减大小
  125. * @return
  126. */
  127. public long decr(String key, long delta) {
  128. if (delta < 0) {
  129. throw new RuntimeException("递减因子必须大于 0");
  130. }
  131. return redisTemplate.opsForValue().increment(key, delta);
  132. }
  133. // String ----------------------- end --------------------------
  134. // Hash ----------------------- start --------------------------
  135. /**
  136. * HashGet
  137. * @param key 键(no null)
  138. * @param item 项(no null)
  139. * @return 值
  140. */
  141. public Object hGet(String key, String item) {
  142. return redisTemplate.opsForHash().get(key, item);
  143. }
  144. /**
  145. * 获取 key 对应的 map
  146. * @param key 键(no null)
  147. * @return 对应的多个键值
  148. */
  149. public Map<Object, Object> hmGet(String key) {
  150. return redisTemplate.opsForHash().entries(key);
  151. }
  152. /**
  153. * HashSet
  154. * @param key 键
  155. * @param map 值
  156. * @return true / false
  157. */
  158. public boolean hmSet(String key, Map<Object, Object> map) {
  159. try {
  160. redisTemplate.opsForHash().putAll(key, map);
  161. return true;
  162. } catch (Exception e) {
  163. e.printStackTrace();
  164. return false;
  165. }
  166. }
  167. /**
  168. * HashSet 并设置时间
  169. * @param key 键
  170. * @param map 值
  171. * @param time 时间
  172. * @return true / false
  173. */
  174. public boolean hmSet(String key, Map<Object, Object> map, long time) {
  175. try {
  176. redisTemplate.opsForHash().putAll(key, map);
  177. if (time > 0) {
  178. expire(key, time);
  179. }
  180. return true;
  181. } catch (Exception e) {
  182. e.printStackTrace();
  183. return false;
  184. }
  185. }
  186. /**
  187. * 向一张 Hash 表 中放入数据,如不存在则创建
  188. * @param key 键
  189. * @param item 项
  190. * @param value 值
  191. * @return true / false
  192. */
  193. public boolean hSet(String key, String item, Object value) {
  194. try {
  195. redisTemplate.opsForHash().put(key, item, value);
  196. return true;
  197. } catch (Exception e) {
  198. e.printStackTrace();
  199. return false;
  200. }
  201. }
  202. /**
  203. * 向一张 Hash 表 中放入数据,并设置时间,如不存在则创建
  204. * @param key 键
  205. * @param item 项
  206. * @param value 值
  207. * @param time 时间(如果原来的 Hash表 设置了时间,这里会覆盖)
  208. * @return true / false
  209. */
  210. public boolean hSet(String key, String item, Object value, long time) {
  211. try {
  212. redisTemplate.opsForHash().put(key, item, value);
  213. if (time > 0) {
  214. expire(key, time);
  215. }
  216. return true;
  217. } catch (Exception e) {
  218. e.printStackTrace();
  219. return false;
  220. }
  221. }
  222. /**
  223. * 删除 Hash 表 中的值
  224. * @param key 键
  225. * @param item 项(可以多个,no null)
  226. */
  227. public void hDel(String key, Object... item) {
  228. redisTemplate.opsForHash().delete(key, item);
  229. }
  230. /**
  231. * 判断 Hash 表 中是否有该键的值
  232. * @param key 键(no null)
  233. * @param item 值(no null)
  234. * @return true / false
  235. */
  236. public boolean hHasKey(String key, String item) {
  237. return redisTemplate.opsForHash().hasKey(key, item);
  238. }
  239. /**
  240. * Hash 递增,如果不存在则创建一个,并把新增的值返回
  241. * @param key 键
  242. * @param item 项
  243. * @param by 递增大小 > 0
  244. * @return
  245. */
  246. public Double hIncr(String key, String item, Double by) {
  247. return redisTemplate.opsForHash().increment(key, item, by);
  248. }
  249. /**
  250. * Hash 递减
  251. * @param key 键
  252. * @param item 项
  253. * @param by 递减大小
  254. * @return
  255. */
  256. public Double hDecr(String key, String item, Double by) {
  257. return redisTemplate.opsForHash().increment(key, item, -by);
  258. }
  259. // Hash ----------------------- end --------------------------
  260. // Set ----------------------- start --------------------------
  261. /**
  262. * 根据 key 获取 set 中的所有值
  263. * @param key 键
  264. * @return 值
  265. */
  266. public Set<Object> sGet(String key) {
  267. try {
  268. return redisTemplate.opsForSet().members(key);
  269. } catch (Exception e) {
  270. e.printStackTrace();
  271. return null;
  272. }
  273. }
  274. /**
  275. * 从键为 key 的 set 中,根据 value 查询是否存在
  276. * @param key 键
  277. * @param value 值
  278. * @return true / false
  279. */
  280. public boolean sHasKey(String key, Object value) {
  281. try {
  282. return redisTemplate.opsForSet().isMember(key, value);
  283. } catch (Exception e) {
  284. e.printStackTrace();
  285. return false;
  286. }
  287. }
  288. /**
  289. * 将数据放入 set 缓存
  290. * @param key 键值
  291. * @param values 值(可以多个)
  292. * @return 成功个数
  293. */
  294. public long sSet(String key, Object... values) {
  295. try {
  296. return redisTemplate.opsForSet().add(key, values);
  297. } catch (Exception e) {
  298. e.printStackTrace();
  299. return 0;
  300. }
  301. }
  302. /**
  303. * 将数据放入 set 缓存,并设置时间
  304. * @param key 键
  305. * @param time 时间
  306. * @param values 值(可以多个)
  307. * @return 成功放入个数
  308. */
  309. public long sSet(String key, long time, Object... values) {
  310. try {
  311. long count = redisTemplate.opsForSet().add(key, values);
  312. if (time > 0) {
  313. expire(key, time);
  314. }
  315. return count;
  316. } catch (Exception e) {
  317. e.printStackTrace();
  318. return 0;
  319. }
  320. }
  321. /**
  322. * 获取 set 缓存的长度
  323. * @param key 键
  324. * @return 长度
  325. */
  326. public long sGetSetSize(String key) {
  327. try {
  328. return redisTemplate.opsForSet().size(key);
  329. } catch (Exception e) {
  330. e.printStackTrace();
  331. return 0;
  332. }
  333. }
  334. /**
  335. * 移除 set 缓存中,值为 value 的
  336. * @param key 键
  337. * @param values 值
  338. * @return 成功移除个数
  339. */
  340. public long setRemove(String key, Object... values) {
  341. try {
  342. return redisTemplate.opsForSet().remove(key, values);
  343. } catch (Exception e) {
  344. e.printStackTrace();
  345. return 0;
  346. }
  347. }
  348. // Set ----------------------- end --------------------------
  349. // List ----------------------- start --------------------------
  350. /**
  351. * 获取 list 缓存的内容
  352. * @param key 键
  353. * @return
  354. */
  355. public List<Object> lGet(String key) {
  356. try {
  357. final long START_INDEX = 0;
  358. final long END_INDEX = 0;
  359. return redisTemplate.opsForList().range(key, START_INDEX, END_INDEX);
  360. } catch (Exception e) {
  361. e.printStackTrace();
  362. return null;
  363. }
  364. }
  365. /**
  366. * 获取 list 缓存的内容
  367. * @param key 键
  368. * @param start 开始
  369. * @param end 结束(0 到 -1 代表所有值)
  370. * @return
  371. */
  372. public List<Object> lGet(String key, long start, long end) {
  373. try {
  374. return redisTemplate.opsForList().range(key, start, end);
  375. } catch (Exception e) {
  376. e.printStackTrace();
  377. return null;
  378. }
  379. }
  380. /**
  381. * 获取 list缓存的长度
  382. * @param key 键
  383. * @return 长度
  384. */
  385. public long lGetListSize(String key) {
  386. try {
  387. return redisTemplate.opsForList().size(key);
  388. } catch (Exception e) {
  389. e.printStackTrace();
  390. return 0;
  391. }
  392. }
  393. /**
  394. * 根据索引 index 获取键为 key 的 list 中的元素
  395. * @param key 键
  396. * @param index 索引
  397. * 当 index >= 0 时 {0:表头, 1:第二个元素}
  398. * 当 index < 0 时 {-1:表尾, -2:倒数第二个元素}
  399. * @return 值
  400. */
  401. public Object lGetIndex(String key, long index) {
  402. try {
  403. return redisTemplate.opsForList().index(key, index);
  404. } catch (Exception e) {
  405. e.printStackTrace();
  406. return null;
  407. }
  408. }
  409. /**
  410. * 将值 value 插入键为 key 的 list 中,如果 list 不存在则创建空 list
  411. * @param key 键
  412. * @param value 值
  413. * @return true / false
  414. */
  415. public boolean lSet(String key, Object value) {
  416. try {
  417. redisTemplate.opsForList().rightPush(key, value);
  418. return true;
  419. } catch (Exception e) {
  420. e.printStackTrace();
  421. return false;
  422. }
  423. }
  424. /**
  425. * 将值 value 插入键为 key 的 list 中,并设置时间
  426. * @param key 键
  427. * @param value 值
  428. * @param time 时间
  429. * @return true / false
  430. */
  431. public boolean lSet(String key, Object value, long time) {
  432. try {
  433. redisTemplate.opsForList().rightPush(key, value);
  434. if (time > 0) {
  435. expire(key, time);
  436. }
  437. return true;
  438. } catch (Exception e) {
  439. e.printStackTrace();
  440. return false;
  441. }
  442. }
  443. /**
  444. * 将 values 插入键为 key 的 list 中
  445. * @param key 键
  446. * @param values 值
  447. * @return true / false
  448. */
  449. public boolean lSetList(String key, List<Object> values) {
  450. try {
  451. redisTemplate.opsForList().rightPushAll(key, values);
  452. return true;
  453. } catch (Exception e) {
  454. e.printStackTrace();
  455. return false;
  456. }
  457. }
  458. /**
  459. * 将 values 插入键为 key 的 list 中,并设置时间
  460. * @param key 键
  461. * @param values 值
  462. * @param time 时间
  463. * @return true / false
  464. */
  465. public boolean lSetList(String key, List<Object> values, long time) {
  466. try {
  467. redisTemplate.opsForList().rightPushAll(key, values);
  468. if (time > 0) {
  469. expire(key, time);
  470. }
  471. return true;
  472. } catch (Exception e) {
  473. e.printStackTrace();
  474. return false;
  475. }
  476. }
  477. /**
  478. * 根据索引 index 修改键为 key 的值
  479. * @param key 键
  480. * @param index 索引
  481. * @param value 值
  482. * @return true / false
  483. */
  484. public boolean lUpdateIndex(String key, long index, Object value) {
  485. try {
  486. redisTemplate.opsForList().set(key, index, value);
  487. return true;
  488. } catch (Exception e) {
  489. e.printStackTrace();
  490. return false;
  491. }
  492. }
  493. /**
  494. * 在键为 key 的 list 中删除值为 value 的元素
  495. * @param key 键
  496. * @param count 如果 count == 0 则删除 list 中所有值为 value 的元素
  497. * 如果 count > 0 则删除 list 中最左边那个值为 value 的元素
  498. * 如果 count < 0 则删除 list 中最右边那个值为 value 的元素
  499. * @param value
  500. * @return
  501. */
  502. public long lRemove(String key, long count, Object value) {
  503. try {
  504. return redisTemplate.opsForList().remove(key, count, value);
  505. } catch (Exception e) {
  506. e.printStackTrace();
  507. return 0;
  508. }
  509. }
  510. // List ----------------------- end --------------------------
  511. }