springboot 整合redis

举报
IT 叶新东老师 发表于 2021/12/31 22:27:42 2021/12/31
【摘要】 发现reids整合了springboot之后搭建起来非常轻松,特意写个教程出来以免后面会忘记,以及自己踩得坑 pom引入maven依赖 # version 版本号一定要加上,否则 RedisTemplate 类会找不到<dependency> <groupId>org.springframework.boot...

发现reids整合了springboot之后搭建起来非常轻松,特意写个教程出来以免后面会忘记,以及自己踩得坑

pom引入maven依赖


  
  1. # version 版本号一定要加上,否则 RedisTemplate 类会找不到
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. <version>2.1.0.RELEASE</version>
  6. </dependency>

另外说明下,我使用的springboot版本是2.1.1,其他版本请自行测试


  
  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.1.RELEASE</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>

application配置文件,配置方式有2种:

yml 配置方式


  
  1. spring:
  2. redis:
  3. host: 192.168.8.162
  4. port: 6379
  5. timeout: 20000
  6. password: woaini
  7. # 集群环境下去掉注释,不用集群请关闭
  8. # cluster:
  9. # nodes: 192.168.211.134:7000,192.168.211.134:7001,192.168.211.134:7002
  10. #默认值是5 一般当此值设置过大时,容易报:Too many Cluster redirections
  11. # maxRedirects: 6
  12. pool:
  13. # 连接池最大连接数(使用负值表示没有限制)
  14. max-active: 8
  15. # 连接池中的最小空闲连接
  16. min-idle: 0
  17. # 连接池中的最大空闲连接
  18. max-idle: 8
  19. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  20. max-wait: -1

properties配置方式


  
  1. #Matser的ip地址
  2. redis.hostName=192.168.177.128
  3. #端口号
  4. redis.port=6382
  5. #如果有密码
  6. redis.password=
  7. #客户端超时时间单位是毫秒 默认是2000
  8. redis.timeout=10000
  9. #最大空闲数
  10. redis.maxIdle=300
  11. #连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal
  12. #redis.maxActive=600
  13. #控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性
  14. redis.maxTotal=1000
  15. #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
  16. redis.maxWaitMillis=1000
  17. #连接的最小空闲时间 默认1800000毫秒(30分钟)
  18. redis.minEvictableIdleTimeMillis=300000
  19. #每次释放连接的最大数目,默认3
  20. redis.numTestsPerEvictionRun=1024
  21. #逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
  22. redis.timeBetweenEvictionRunsMillis=30000
  23. #是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
  24. redis.testOnBorrow=true
  25. #在空闲时检查有效性, 默认false
  26. redis.testWhileIdle=true #redis集群配置
  27. spring.redis.cluster.nodes=192.168.177.128:7001,192.168.177.128:7002,192.168.177.128:7003,192.168.177.128:7004,192.168.177.128:7005,192.168.177.128:7006 spring.redis.cluster.max-redirects=3
  28. #哨兵模式
  29. #redis.sentinel.host1=192.168.177.128
  30. #redis.sentinel.port1=26379
  31. #redis.sentinel.host2=172.20.1.231
  32. #redis.sentinel.port2=26379

配置类


  
  1. package com.icode.common.web.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import com.alibaba.druid.support.http.StatViewServlet;
  4. import com.alibaba.druid.support.http.WebStatFilter;
  5. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  6. import com.fasterxml.jackson.annotation.PropertyAccessor;
  7. import com.fasterxml.jackson.databind.ObjectMapper;
  8. import com.github.pagehelper.PageHelper;
  9. import org.springframework.boot.context.properties.ConfigurationProperties;
  10. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  11. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  12. import org.springframework.context.annotation.Bean;
  13. import org.springframework.context.annotation.Configuration;
  14. import org.springframework.data.redis.connection.RedisConnectionFactory;
  15. import org.springframework.data.redis.core.RedisTemplate;
  16. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  17. import org.springframework.data.redis.serializer.StringRedisSerializer;
  18. import javax.sql.DataSource;
  19. import java.util.Arrays;
  20. import java.util.HashMap;
  21. import java.util.Map;
  22. import java.util.Properties;
  23. @Configuration
  24. public class WebDefaultConfig {
  25. /**
  26. * redis配置
  27. * @param factory
  28. * @return
  29. */
  30. @Bean
  31. @SuppressWarnings("all")
  32. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  33. RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
  34. template.setConnectionFactory(factory);
  35. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  36. ObjectMapper om = new ObjectMapper();
  37. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  38. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  39. jackson2JsonRedisSerializer.setObjectMapper(om);
  40. StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
  41. // key采用String的序列化方式
  42. template.setKeySerializer(stringRedisSerializer);
  43. // hash的key也采用String的序列化方式
  44. template.setHashKeySerializer(stringRedisSerializer);
  45. // value序列化方式采用jackson
  46. template.setValueSerializer(jackson2JsonRedisSerializer);
  47. // hash的value序列化方式采用jackson
  48. template.setHashValueSerializer(jackson2JsonRedisSerializer);
  49. template.afterPropertiesSet();
  50. return template;
  51. }
  52. }

添加一个操作redis的服务类


  
  1. package com.icode.common.web.service;
  2. import com.icode.common.base.WebBaseService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.data.redis.core.RedisTemplate;
  5. import org.springframework.stereotype.Service;
  6. import org.springframework.util.CollectionUtils;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Set;
  10. import java.util.concurrent.TimeUnit;
  11. /**
  12. * 缓存服务类
  13. */
  14. @Service(value = "WebCacheService")
  15. public class WebCacheService extends WebBaseService {
  16. @Autowired
  17. private RedisTemplate<String, Object> redisTemplate;
  18. //=============================common============================
  19. /**
  20. * 指定缓存失效时间
  21. *
  22. * @param key 键
  23. * @param time 时间(秒)
  24. * @return
  25. */
  26. public boolean expire(String key, long time) {
  27. try {
  28. if (time > 0) {
  29. redisTemplate.expire(key, time, TimeUnit.SECONDS);
  30. }
  31. return true;
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. return false;
  35. }
  36. }
  37. /**
  38. * 根据key 获取过期时间
  39. *
  40. * @param key 键 不能为null
  41. * @return 时间(秒) 返回0代表为永久有效 ,返回-1表示未设置过期时间(即永久存在),返回-2表示key不存在
  42. */
  43. public long getExpire(String key) {
  44. return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  45. }
  46. /**
  47. * 判断key是否存在
  48. *
  49. * @param key 键
  50. * @return true 存在 false不存在
  51. */
  52. public boolean hasKey(String key) {
  53. try {
  54. return redisTemplate.hasKey(key);
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. return false;
  58. }
  59. }
  60. /**
  61. * 删除缓存
  62. *
  63. * @param key 可以传一个值 或多个
  64. */
  65. @SuppressWarnings("unchecked")
  66. public void del(String... key) {
  67. if (key != null && key.length > 0) {
  68. if (key.length == 1) {
  69. redisTemplate.delete(key[0]);
  70. } else {
  71. redisTemplate.delete(CollectionUtils.arrayToList(key));
  72. }
  73. }
  74. }
  75. //============================String=============================
  76. /**
  77. * 普通缓存获取
  78. *
  79. * @param key 键
  80. * @return
  81. */
  82. public Object get(String key) {
  83. return key == null ? null : redisTemplate.opsForValue().get(key);
  84. }
  85. /**
  86. * 普通缓存放入,未设置时间的情况下此值永久存在
  87. *
  88. * @param key 键
  89. * @param value 值
  90. * @return true成功 false失败
  91. */
  92. public boolean set(String key, Object value) {
  93. try {
  94. redisTemplate.opsForValue().set(key, value);
  95. return true;
  96. } catch (Exception e) {
  97. e.printStackTrace();
  98. return false;
  99. }
  100. }
  101. /**
  102. * 普通缓存放入并设置时间
  103. *
  104. * @param key 键
  105. * @param value 值
  106. * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
  107. * @return true成功 false 失败
  108. */
  109. public boolean set(String key, Object value, long time) {
  110. try {
  111. if (time > 0) {
  112. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  113. } else {
  114. set(key, value);
  115. }
  116. return true;
  117. } catch (Exception e) {
  118. e.printStackTrace();
  119. return false;
  120. }
  121. }
  122. /**
  123. * 递增
  124. *
  125. * @param key 键
  126. * @param delta 要增加几(大于0)
  127. * @return
  128. */
  129. public long incr(String key, long delta) {
  130. if (delta < 0) {
  131. throw new RuntimeException("递增因子必须大于0");
  132. }
  133. return redisTemplate.opsForValue().increment(key, delta);
  134. }
  135. /**
  136. * 递减
  137. *
  138. * @param key 键
  139. * @param delta 要减少几(小于0)
  140. * @return
  141. */
  142. public long decr(String key, long delta) {
  143. if (delta < 0) {
  144. throw new RuntimeException("递减因子必须大于0");
  145. }
  146. return redisTemplate.opsForValue().increment(key, -delta);
  147. }
  148. //================================Map=================================
  149. /**
  150. * HashGet
  151. *
  152. * @param key 键 不能为null
  153. * @param item 项 不能为null
  154. * @return
  155. */
  156. public Object hget(String key, String item) {
  157. return redisTemplate.opsForHash().get(key, item);
  158. }
  159. /**
  160. * 获取hashKey对应的所有键值
  161. *
  162. * @param key 键
  163. * @return 对应的多个键值
  164. */
  165. public Map<Object, Object> hmget(String key) {
  166. return redisTemplate.opsForHash().entries(key);
  167. }
  168. /**
  169. * HashSet
  170. *
  171. * @param key 键
  172. * @param map 对应多个键值
  173. * @return true 成功 false 失败
  174. */
  175. public boolean hmset(String key, Map<String, Object> map) {
  176. try {
  177. redisTemplate.opsForHash().putAll(key, map);
  178. return true;
  179. } catch (Exception e) {
  180. e.printStackTrace();
  181. return false;
  182. }
  183. }
  184. /**
  185. * HashSet 并设置时间
  186. *
  187. * @param key 键
  188. * @param map 对应多个键值
  189. * @param time 时间(秒)
  190. * @return true成功 false失败
  191. */
  192. public boolean hmset(String key, Map<String, Object> map, long time) {
  193. try {
  194. redisTemplate.opsForHash().putAll(key, map);
  195. if (time > 0) {
  196. expire(key, time);
  197. }
  198. return true;
  199. } catch (Exception e) {
  200. e.printStackTrace();
  201. return false;
  202. }
  203. }
  204. /**
  205. * 向一张hash表中放入数据,如果不存在将创建
  206. *
  207. * @param key 键
  208. * @param item 项
  209. * @param value 值
  210. * @return true 成功 false失败
  211. */
  212. public boolean hset(String key, String item, Object value) {
  213. try {
  214. redisTemplate.opsForHash().put(key, item, value);
  215. return true;
  216. } catch (Exception e) {
  217. e.printStackTrace();
  218. return false;
  219. }
  220. }
  221. /**
  222. * 向一张hash表中放入数据,如果不存在将创建
  223. *
  224. * @param key 键
  225. * @param item 项
  226. * @param value 值
  227. * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  228. * @return true 成功 false失败
  229. */
  230. public boolean hset(String key, String item, Object value, long time) {
  231. try {
  232. redisTemplate.opsForHash().put(key, item, value);
  233. if (time > 0) {
  234. expire(key, time);
  235. }
  236. return true;
  237. } catch (Exception e) {
  238. e.printStackTrace();
  239. return false;
  240. }
  241. }
  242. /**
  243. * 删除hash表中的值
  244. *
  245. * @param key 键 不能为null
  246. * @param item 项 可以使多个 不能为null
  247. */
  248. public void hdel(String key, Object... item) {
  249. redisTemplate.opsForHash().delete(key, item);
  250. }
  251. /**
  252. * 判断hash表中是否有该项的值
  253. *
  254. * @param key 键 不能为null
  255. * @param item 项 不能为null
  256. * @return true 存在 false不存在
  257. */
  258. public boolean hHasKey(String key, String item) {
  259. return redisTemplate.opsForHash().hasKey(key, item);
  260. }
  261. /**
  262. * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  263. *
  264. * @param key 键
  265. * @param item 项
  266. * @param by 要增加几(大于0)
  267. * @return
  268. */
  269. public double hincr(String key, String item, double by) {
  270. return redisTemplate.opsForHash().increment(key, item, by);
  271. }
  272. /**
  273. * hash递减
  274. *
  275. * @param key 键
  276. * @param item 项
  277. * @param by 要减少记(小于0)
  278. * @return
  279. */
  280. public double hdecr(String key, String item, double by) {
  281. return redisTemplate.opsForHash().increment(key, item, -by);
  282. } //============================set============================
  283. /**
  284. * 根据key获取Set中的所有值
  285. *
  286. * @param key 键
  287. * @return
  288. */
  289. public Set<Object> sGet(String key) {
  290. try {
  291. return redisTemplate.opsForSet().members(key);
  292. } catch (Exception e) {
  293. e.printStackTrace();
  294. return null;
  295. }
  296. }
  297. /**
  298. * 根据value从一个set中查询,是否存在
  299. *
  300. * @param key 键
  301. * @param value 值
  302. * @return true 存在 false不存在
  303. */
  304. public boolean sHasKey(String key, Object value) {
  305. try {
  306. return redisTemplate.opsForSet().isMember(key, value);
  307. } catch (Exception e) {
  308. e.printStackTrace();
  309. return false;
  310. }
  311. }
  312. /**
  313. * 将数据放入set缓存
  314. *
  315. * @param key 键
  316. * @param values 值 可以是多个
  317. * @return 成功个数
  318. */
  319. public long sSet(String key, Object... values) {
  320. try {
  321. return redisTemplate.opsForSet().add(key, values);
  322. } catch (Exception e) {
  323. e.printStackTrace();
  324. return 0;
  325. }
  326. }
  327. /**
  328. * 将set数据放入缓存
  329. *
  330. * @param key 键
  331. * @param time 时间(秒)
  332. * @param values 值 可以是多个
  333. * @return 成功个数
  334. */
  335. public long sSetAndTime(String key, long time, Object... values) {
  336. try {
  337. Long count = redisTemplate.opsForSet().add(key, values);
  338. if (time > 0) expire(key, time);
  339. return count;
  340. } catch (Exception e) {
  341. e.printStackTrace();
  342. return 0;
  343. }
  344. }
  345. /**
  346. * 获取set缓存的长度
  347. *
  348. * @param key 键
  349. * @return
  350. */
  351. public long sGetSetSize(String key) {
  352. try {
  353. return redisTemplate.opsForSet().size(key);
  354. } catch (Exception e) {
  355. e.printStackTrace();
  356. return 0;
  357. }
  358. }
  359. /**
  360. * 移除值为value的
  361. *
  362. * @param key 键
  363. * @param values 值 可以是多个
  364. * @return 移除的个数
  365. */
  366. public long setRemove(String key, Object... values) {
  367. try {
  368. Long count = redisTemplate.opsForSet().remove(key, values);
  369. return count;
  370. } catch (Exception e) {
  371. e.printStackTrace();
  372. return 0;
  373. }
  374. }
  375. //===============================list=================================
  376. /**
  377. * 获取list缓存的内容
  378. *
  379. * @param key 键
  380. * @param start 开始
  381. * @param end 结束 0 到 -1代表所有值
  382. * @return
  383. */
  384. public List<Object> lGet(String key, long start, long end) {
  385. try {
  386. return redisTemplate.opsForList().range(key, start, end);
  387. } catch (Exception e) {
  388. e.printStackTrace();
  389. return null;
  390. }
  391. }
  392. /**
  393. * 获取list缓存的长度
  394. *
  395. * @param key 键
  396. * @return
  397. */
  398. public long lGetListSize(String key) {
  399. try {
  400. return redisTemplate.opsForList().size(key);
  401. } catch (Exception e) {
  402. e.printStackTrace();
  403. return 0;
  404. }
  405. }
  406. /**
  407. * 通过索引 获取list中的值
  408. *
  409. * @param key 键
  410. * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  411. * @return
  412. */
  413. public Object lGetIndex(String key, long index) {
  414. try {
  415. return redisTemplate.opsForList().index(key, index);
  416. } catch (Exception e) {
  417. e.printStackTrace();
  418. return null;
  419. }
  420. }
  421. /**
  422. * 将list放入缓存
  423. *
  424. * @param key 键
  425. * @param value 值
  426. * @return
  427. */
  428. public boolean lSet(String key, Object value) {
  429. try {
  430. redisTemplate.opsForList().rightPush(key, value);
  431. return true;
  432. } catch (Exception e) {
  433. e.printStackTrace();
  434. return false;
  435. }
  436. }
  437. /**
  438. * 将list放入缓存
  439. *
  440. * @param key 键
  441. * @param value 值
  442. * @param time 时间(秒)
  443. * @return
  444. */
  445. public boolean lSet(String key, Object value, long time) {
  446. try {
  447. redisTemplate.opsForList().rightPush(key, value);
  448. if (time > 0) expire(key, time);
  449. return true;
  450. } catch (Exception e) {
  451. e.printStackTrace();
  452. return false;
  453. }
  454. }
  455. /**
  456. * 将list放入缓存
  457. *
  458. * @param key 键
  459. * @param value 值
  460. * @return
  461. */
  462. public boolean lSet(String key, List<Object> value) {
  463. try {
  464. redisTemplate.opsForList().rightPushAll(key, value);
  465. return true;
  466. } catch (Exception e) {
  467. e.printStackTrace();
  468. return false;
  469. }
  470. }
  471. /**
  472. * 将list放入缓存
  473. *
  474. * @param key 键
  475. * @param value 值
  476. * @param time 时间(秒)
  477. * @return
  478. */
  479. public boolean lSet(String key, List<Object> value, long time) {
  480. try {
  481. redisTemplate.opsForList().rightPushAll(key, value);
  482. if (time > 0) expire(key, time);
  483. return true;
  484. } catch (Exception e) {
  485. e.printStackTrace();
  486. return false;
  487. }
  488. }
  489. /**
  490. * 根据索引修改list中的某条数据
  491. *
  492. * @param key 键
  493. * @param index 索引
  494. * @param value 值
  495. * @return
  496. */
  497. public boolean lUpdateIndex(String key, long index, Object value) {
  498. try {
  499. redisTemplate.opsForList().set(key, index, value);
  500. return true;
  501. } catch (Exception e) {
  502. e.printStackTrace();
  503. return false;
  504. }
  505. }
  506. /**
  507. * 移除N个值为value
  508. *
  509. * @param key 键
  510. * @param count 移除多少个
  511. * @param value 值
  512. * @return 移除的个数
  513. */
  514. public long lRemove(String key, long count, Object value) {
  515. try {
  516. Long remove = redisTemplate.opsForList().remove(key, count, value);
  517. return remove;
  518. } catch (Exception e) {
  519. e.printStackTrace();
  520. return 0;
  521. }
  522. }
  523. }

大功告成,

文章来源: yexindong.blog.csdn.net,作者:java叶新东老师,版权归原作者所有,如需转载,请联系作者。

原文链接:yexindong.blog.csdn.net/article/details/85034526

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。