当前位置:   article > 正文

SpringBoot maven环境下整合redis_springboot maven redis

springboot maven redis

一 前期准备

1.SpringBoot项目+maven环境
2.安装好redis服务,并启动(本教程适合 单机,集群,哨兵模式的redis服务)

二 配置依赖

  1. <!--redis依赖-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>
  6. <!--web开发支持-->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-web</artifactId>
  10. </dependency>
  11. <!--测试支持-->
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-test</artifactId>
  15. <scope>test</scope>
  16. </dependency>

备注:eclipse通过sts SpringBoot 构建工具添加 web 与 nosql-redis  此依赖可以自动生成

          idea 通过 Spring Initializr 也可以选定 web 与 nosql-redis 此依赖可以自动生成


三 redis配置

1.项目目录结构


2.SpringBoot 配置文件 配置redis 信息

  1. #========== 服务器 配置信息===========#
  2. #服务器端口映射
  3. server.port=8099
  4. #服务项目名
  5. server.servlet.path=/SpringBoot-redis
  6. #==========redis 配置信息===========#
  7. #(单机redis)数据库ip
  8. #spring.redis.host=127.0.0.1
  9. #(单机redis)数据库端口
  10. #spring.redis.port= 6379
  11. #(cluster集群,不使用则不用开启)在群集中执行命令时要遵循的最大重定向数目。
  12. spring.redis.cluster.max-redirects=3
  13. #(cluster集群,不使用则不用开启)以逗号分隔的“主机:端口”对列表进行引导。
  14. spring.redis.cluster.nodes=127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005
  15. #(哨兵模式,不使用则不用开启)Redis服务器的名称。
  16. # spring.redis.sentinel.master=
  17. #(哨兵模式,不使用则不用开启)主机:端口对的逗号分隔列表。
  18. # spring.redis.sentinel.nodes=
  19. #数据库指定索引
  20. spring.redis.database= 1
  21. #数据库密码
  22. spring.redis.password=
  23. #超时时间
  24. spring.redis.timeout= 5000
  25. #连接池最大连接数,负值表示不限制
  26. spring.redis.jedis.pool.max-active= 1000
  27. #连接池中最大空闲连接
  28. spring.redis.jedis.pool.max-idle= 10
  29. #连接池中最小空闲连接
  30. spring.redis.jedis.pool.min-idle= 2
  31. #连接池最大阻塞等待时间,负值表示不限制
  32. spring.redis.jedis.pool.max-wait= -1

3.redis配置集

RedisUtil.java

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

备注:此工具类包含大部分操作。


RedisConfig.java

  1. package com.zyj.redis;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.data.redis.connection.RedisConnectionFactory;
  5. import org.springframework.data.redis.core.RedisTemplate;
  6. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  7. import org.springframework.data.redis.serializer.StringRedisSerializer;
  8. /**
  9. *@Description: redis配置文件
  10. *@Author: zyj 2018/5/26 8:06
  11. */
  12. @Configuration
  13. public class RedisConfig {
  14. /**
  15. * 实例化 RedisTemplate 对象
  16. * 提供给 RedisUtil 使用
  17. * @param redisConnectionFactory springboot配置好的连接工厂
  18. * @return RedisTemplate
  19. * @autor zyj
  20. * @date 2018年5月26日 08:47:27
  21. */
  22. @Bean
  23. public RedisTemplate<String, Object> RedisTemplate(RedisConnectionFactory redisConnectionFactory) {
  24. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  25. initRedisTemplate(redisTemplate, redisConnectionFactory);
  26. return redisTemplate;
  27. }
  28. /**
  29. * 设置数据存入 redis 的序列化方式,并开启事务
  30. *
  31. * @param redisTemplate
  32. * @param factory
  33. * @autor zyj
  34. * @date 2018年5月26日 08:47:27
  35. */
  36. private void initRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
  37. //如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!
  38. redisTemplate.setKeySerializer(new StringRedisSerializer());
  39. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  40. redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
  41. redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  42. // 开启事务
  43. redisTemplate.setEnableTransactionSupport(true);
  44. redisTemplate.setConnectionFactory(factory);
  45. }
  46. /**
  47. * 注入封装RedisTemplate 给RedisUtil提供操作类
  48. * @param redisTemplate
  49. * @return RedisUtil
  50. * @autor zyj
  51. * @date 2018年5月26日 08:47:27
  52. */
  53. @Bean(name = "redisUtil")
  54. public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
  55. RedisUtil redisUtil = new RedisUtil();
  56. redisUtil.setRedisTemplate(redisTemplate);
  57. return redisUtil;
  58. }
  59. }

备注:此类配置了redis的操作对象 RedisTemplate并将RedisUtil实例化到容器中

四 redis测试

1.建立测试类

  1. package com.zyj.redis;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. /**
  7. *@Description: redis 测试
  8. *@Author: zyj 2018/5/26 8:12
  9. */
  10. @Controller
  11. @RequestMapping("/redisTest")
  12. public class RedisTestController {
  13. @Autowired
  14. RedisUtil redisUtil;
  15. /**
  16. *@Description: 测试redis
  17. *@param key, value
  18. *@return Object
  19. *@Author: zyj 2018/5/26 8:46
  20. */
  21. @RequestMapping("/testRedisAdd")
  22. @ResponseBody
  23. Object testRedisAdd(String key,String value){
  24. redisUtil.set(key,value);
  25. return redisUtil.get(key);
  26. }
  27. }

2.测试

启动springBoot项目SpringbootRedisApplication,网址中输入

http://localhost:8099/SpringBoot-redis/redisTest/testRedisAdd?key=1&value=244


备注:http://服务器ip:端口/服务器跟路径/测试类控制器/测试方法?参数1= &参数2= 


3.验证

使用redis客户端连接redis服务


依次验证数据



祝你成功!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/457674
推荐阅读
相关标签
  

闽ICP备14008679号