转载:https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html

不是使用注解而是代码调用

需要在springboot项目加入的依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-data-redis</artifactId>
  8. </dependency>

application.properties中加入redis相关配置

  1. # Redis数据库索引(默认为0)
  2. spring.redis.database=0
  3. # Redis服务器地址
  4. spring.redis.host=192.168.0.24
  5. # Redis服务器连接端口
  6. spring.redis.port=6379
  7. # Redis服务器连接密码(默认为空)
  8. spring.redis.password=
  9. # 连接池最大连接数(使用负值表示没有限制)
  10. spring.redis.pool.max-active=200
  11. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  12. spring.redis.pool.max-wait=-1
  13. # 连接池中的最大空闲连接
  14. spring.redis.pool.max-idle=10
  15. # 连接池中的最小空闲连接
  16. spring.redis.pool.min-idle=0
  17. # 连接超时时间(毫秒)
  18. spring.redis.timeout=1000

redis的模板配置

原文提到redis自动配置的模板不好用,自己手动配置的

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.data.redis.connection.RedisConnectionFactory;
  4. import org.springframework.data.redis.core.RedisTemplate;
  5. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  6. import org.springframework.data.redis.serializer.StringRedisSerializer;
  7.  
  8. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  9. import com.fasterxml.jackson.annotation.PropertyAccessor;
  10. import com.fasterxml.jackson.databind.ObjectMapper;
  11.  
  12. /**
  13. * redis配置类
  14. * @author ZENG.XIAO.YAN
  15. * @date 2018年6月6日
  16. *
  17. */
  18. @Configuration
  19. public class RedisConfig {
  20.  
  21. @Bean
  22. @SuppressWarnings("all")
  23. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  24. RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
  25. template.setConnectionFactory(factory);
  26. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  27. ObjectMapper om = new ObjectMapper();
  28. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  29. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  30. jackson2JsonRedisSerializer.setObjectMapper(om);
  31. StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
  32. // key采用String的序列化方式
  33. template.setKeySerializer(stringRedisSerializer);
  34. // hash的key也采用String的序列化方式
  35. template.setHashKeySerializer(stringRedisSerializer);
  36. // value序列化方式采用jackson
  37. template.setValueSerializer(jackson2JsonRedisSerializer);
  38. // hash的value序列化方式采用jackson
  39. template.setHashValueSerializer(jackson2JsonRedisSerializer);
  40. template.afterPropertiesSet();
  41. return template;
  42. }
  43.  
  44. }

写一个Redis工具类

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

在做项目时需要适配移动端,session存储验证码没法取到,学了 非常感谢原文

SpringBoot中集成redis的更多相关文章

  1. springboot中集成memcached

    前言 Memcached 是一个高性能的分布式内存对象缓存系统,其存储性能在某些方面不比redis差,甚至在文本类型数据的存储上性能略优于redis,本文将介绍如何在springboot中集成memc ...

  2. SpringBoot中整合Redis、Ehcache使用配置切换 并且整合到Shiro中

    在SpringBoot中Shiro缓存使用Redis.Ehcache实现的两种方式实例 SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这sh ...

  3. 由浅入深学习springboot中使用redis

    很多时候,我们会在springboot中配置redis,但是就那么几个配置就配好了,没办法知道为什么,这里就详细的讲解一下 这里假设已经成功创建了一个springboot项目. redis连接工厂类 ...

  4. (一)由浅入深学习springboot中使用redis

    很多时候,我们会在springboot中配置redis,但是就那么几个配置就配好了,没办法知道为什么,这里就详细的讲解一下 这里假设已经成功创建了一个springboot项目. redis连接工厂类 ...

  5. SpringBoot中使用Redis

    在SpringBoot中使用Redis,思路如下: 查询时先查Redis缓存,如果缓存中存在信息,就直接从缓存中获取. 如果缓存中没有相关信息,就去数据库中查找,查完顺便将信息存放进缓存里,以便下一次 ...

  6. 在springboot中使用redis缓存,将缓存序列化为json格式的数据

    背景 在springboot中使用redis缓存结合spring缓存注解,当缓存成功后使用gui界面查看redis中的数据 原因 springboot缓存默认的序列化是jdk提供的 Serializa ...

  7. Spring Boot 中集成 Redis 作为数据缓存

    只添加注解:@Cacheable,不配置key时,redis 中默认存的 key 是:users::SimpleKey [](1.redis-cli 中,通过命令:keys * 查看:2.key:缓存 ...

  8. 在springboot中集成mybatis开发

    在springboot中利用mybatis框架进行开发需要集成mybatis才能进行开发,那么如何在springboot中集成mybatis呢?按照以下几个步骤就可以实现springboot集成myb ...

  9. 在springboot中集成jsp开发

    springboot就是一个升级版的spring.它可以极大的简化xml配置文件,可以采用全注解形式开发,一个字就是很牛.在springboot想要使用jsp开发,需要集成jsp,在springboo ...

随机推荐

  1. 国内最火的10款Java开源项目,都是国人开发,CMS居多

    原文链接:https://www.cnblogs.com/jimcsharp/p/8266954.html 国内的开源环境已经相当好,但是国内开发注重是应用,创新有但不多,从榜单可以看出,专门搞技术的 ...

  2. 手绘raft算法

    手绘raft算法 互联网技术窝 2019-04-07 12:06:05 在现实的分布式系统中,不能可能保证集群中的每一台机器都是100%可用可靠的,集群中的任何机器都可能发生宕机.网络连接等问题导致集 ...

  3. 茶杯头开枪ahk代码

    ;说明这个工具是为了茶杯头写的,F1表示换枪攻击,F3表示不换枪攻击,F2表示停止攻击. $F1::loop{ GetKeyState, state, F2, Pif state = D{break ...

  4. web网站使用qq第三方登录

    Html代码: <a href=’/QQlogin’>qq登录</a> //后台代码: @RequestMapping(value = "/QQlogin" ...

  5. MongoDB学习记录(三) - MongoDB的"增查改删"操作之"查"

    查找使用的方法: db.collection.find() 查找所有文档 db.collection.find({})或者db.collection.find({}) 指定键值对 db.collect ...

  6. idea配置.gitignore后无法起作用

    1)要先进入项目包所在的文件夹 2)git rm -r --cached . ://后面有个点3)git add . ;后面有个点4)git commit -m  "update .giti ...

  7. 修改Macros的值

    修改模板的macro  修改对应主机的macro

  8. zabbix 自带监控项报性能问题解决方法

    类似报警信息为:Zabbix discoverer processes more than 75% busy 解决方法:修改zabbix_server配置 原因:每个discovery任务在一定时间内 ...

  9. python opencv 处理文件、摄像头、图形化界面

    转换成RGB import cv2 import numpy as ny img = ny.zeros( ( 3 , 3 ),ny.float32) img=cv2.cvtColor(img,cv2. ...

  10. Leetcode(一)两数之和

    1.两数之和 题目要求: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重 ...