RedisUtil.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. package com.bootdo.common.utils;
  2. import org.springframework.data.redis.connection.RedisConnection;
  3. import org.springframework.data.redis.connection.RedisStringCommands;
  4. import org.springframework.data.redis.core.RedisTemplate;
  5. import org.springframework.data.redis.core.ValueOperations;
  6. import org.springframework.data.redis.support.atomic.RedisAtomicLong;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Set;
  10. import java.util.concurrent.TimeUnit;
  11. /**
  12. * redis工具
  13. */
  14. public class RedisUtil {
  15. private RedisTemplate<String, Object> redisTemplate;
  16. public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
  17. this.redisTemplate = redisTemplate;
  18. }
  19. //=============================common============================
  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. * @param key 键 不能为null
  40. * @return 时间(秒) 返回0代表为永久有效
  41. */
  42. public long getExpire(String key){
  43. return redisTemplate.getExpire(key,TimeUnit.SECONDS);
  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. * @param key 可以传一个值 或多个
  61. */
  62. @SuppressWarnings("unchecked")
  63. public void del(String key){
  64. redisTemplate.delete(key);
  65. }
  66. /**
  67. * 删除缓存
  68. * @param key 可以传一个值 或多个
  69. */
  70. @SuppressWarnings("unchecked")
  71. public void del(byte[] key){
  72. redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.del(key));
  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. public byte[] get(byte[] key) {
  84. // 使用了lambda表达式
  85. return redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.get(key));
  86. }
  87. /**
  88. * 普通缓存获取并刷新过期时间
  89. * @param key 键
  90. * @return 值
  91. */
  92. public Object getAndRefresh(String key,Long seconds){
  93. Object object = key==null?null:redisTemplate.opsForValue().get(key);
  94. try {
  95. redisTemplate.opsForValue().set(key, object,seconds,TimeUnit.SECONDS);
  96. } catch (Exception e) {
  97. e.printStackTrace();
  98. }
  99. return object;
  100. }
  101. /**
  102. * 普通缓存放入
  103. * @param key 键
  104. * @param value 值
  105. * @return true成功 false失败
  106. */
  107. public boolean set(String key,Object value) {
  108. try {
  109. redisTemplate.opsForValue().set(key, value);
  110. return true;
  111. } catch (Exception e) {
  112. e.printStackTrace();
  113. return false;
  114. }
  115. }
  116. public byte[] set(byte[] key,byte[] value) {
  117. // 使用了lambda表达式
  118. redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.set(key,value));
  119. return value;
  120. }
  121. public byte[] set(byte[] key,byte[] value,long time) {
  122. // 使用了lambda表达式
  123. redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.set(key,value)) ;
  124. redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.expire(key,time));
  125. return value;
  126. }
  127. public void expire(byte[] key,long time ) {
  128. // 使用了lambda表达式
  129. redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.expire(key,time));
  130. }
  131. public Long dbSize() {
  132. // 使用了lambda表达式
  133. return redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.dbSize());
  134. }
  135. public Set<byte[]> keys(byte[] pattern) {
  136. // 使用了lambda表达式
  137. return redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.keys(pattern));
  138. }
  139. /**
  140. * 普通缓存放入并设置时间
  141. * @param key 键
  142. * @param value 值
  143. * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
  144. * @return true成功 false 失败
  145. */
  146. public boolean set(String key,Object value,long time){
  147. try {
  148. if(time>0){
  149. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  150. }else{
  151. set(key, value);
  152. }
  153. return true;
  154. } catch (Exception e) {
  155. e.printStackTrace();
  156. return false;
  157. }
  158. }
  159. /**
  160. * 使用Redis生成全局唯一自增ID
  161. */
  162. public long generate(String key) {
  163. RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
  164. return redisAtomicLong.incrementAndGet();
  165. }
  166. /**
  167. * 递增
  168. * @param key 键
  169. * @param delta 要增加几(大于0)
  170. * @return
  171. */
  172. public long incr(String key, long delta){
  173. if(delta<0){
  174. throw new RuntimeException("递增因子必须大于0");
  175. }
  176. return redisTemplate.opsForValue().increment(key, delta);
  177. }
  178. /**
  179. * 递减
  180. * @param key 键
  181. * @param delta 要减少几(小于0)
  182. * @return
  183. */
  184. public long decr(String key, long delta){
  185. if(delta<0){
  186. throw new RuntimeException("递减因子必须大于0");
  187. }
  188. return redisTemplate.opsForValue().increment(key, -delta);
  189. }
  190. //================================Map=================================
  191. /**
  192. * HashGet
  193. * @param key 键 不能为null
  194. * @param item 项 不能为null
  195. * @return 值
  196. */
  197. public Object hget(String key,String item){
  198. return redisTemplate.opsForHash().get(key, item);
  199. }
  200. /**
  201. * 获取所有的值
  202. * @param key
  203. * @return
  204. */
  205. public List<Object> hgetValues(String key){
  206. return redisTemplate.opsForHash().values(key);
  207. }
  208. /**
  209. * 获取hashKey对应的所有键值
  210. * @param key 键
  211. * @return 对应的多个键值
  212. */
  213. public Map<Object,Object> hmget(String key){
  214. return redisTemplate.opsForHash().entries(key);
  215. }
  216. /**
  217. *
  218. *
  219. * HashSet
  220. * @param key 键
  221. * @param map 对应多个键值
  222. * @return true 成功 false 失败
  223. */
  224. public boolean hmset(String key, Map<String,Object> map){
  225. try {
  226. redisTemplate.opsForHash().putAll(key, map);
  227. return true;
  228. } catch (Exception e) {
  229. e.printStackTrace();
  230. return false;
  231. }
  232. }
  233. /**
  234. * HashSet 并设置时间
  235. * @param key 键
  236. * @param map 对应多个键值
  237. * @param time 时间(秒)
  238. * @return true成功 false失败
  239. */
  240. public boolean hmset(String key, Map<String,Object> map, long time){
  241. try {
  242. redisTemplate.opsForHash().putAll(key, map);
  243. if(time>0){
  244. expire(key, time);
  245. }
  246. return true;
  247. } catch (Exception e) {
  248. e.printStackTrace();
  249. return false;
  250. }
  251. }
  252. /**
  253. * 向一张hash表中放入数据,如果不存在将创建
  254. * @param key 键
  255. * @param item 项
  256. * @param value 值
  257. * @return true 成功 false失败
  258. */
  259. public boolean hset(String key,String item,Object value) {
  260. try {
  261. redisTemplate.opsForHash().put(key, item, value);
  262. return true;
  263. } catch (Exception e) {
  264. e.printStackTrace();
  265. return false;
  266. }
  267. }
  268. /**
  269. * 向一张hash表中放入数据,如果不存在将创建
  270. * @param key 键
  271. * @param item 项
  272. * @param value 值
  273. * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  274. * @return true 成功 false失败
  275. */
  276. public boolean hset(String key,String item,Object value,long time) {
  277. try {
  278. redisTemplate.opsForHash().put(key, item, value);
  279. if(time>0){
  280. expire(key, time);
  281. }
  282. return true;
  283. } catch (Exception e) {
  284. e.printStackTrace();
  285. return false;
  286. }
  287. }
  288. /**
  289. * 删除hash表中的值
  290. * @param key 键 不能为null
  291. * @param item 项 可以使多个 不能为null
  292. */
  293. public void hdel(String key, Object... item){
  294. redisTemplate.opsForHash().delete(key,item);
  295. }
  296. /**
  297. * 判断hash表中是否有该项的值
  298. * @param key 键 不能为null
  299. * @param item 项 不能为null
  300. * @return true 存在 false不存在
  301. */
  302. public boolean hHasKey(String key, String item){
  303. return redisTemplate.opsForHash().hasKey(key, item);
  304. }
  305. /**
  306. * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  307. * @param key 键
  308. * @param item 项
  309. * @param by 要增加几(大于0)
  310. * @return
  311. */
  312. public double hincr(String key, String item,double by){
  313. return redisTemplate.opsForHash().increment(key, item, by);
  314. }
  315. /**
  316. * hash递减
  317. * @param key 键
  318. * @param item 项
  319. * @param by 要减少记(小于0)
  320. * @return
  321. */
  322. public double hdecr(String key, String item,double by){
  323. return redisTemplate.opsForHash().increment(key, item,-by);
  324. }
  325. //============================set=============================
  326. /**
  327. * 根据key获取Set中的所有值
  328. * @param key 键
  329. * @return
  330. */
  331. public Set<Object> sGet(String key){
  332. try {
  333. return redisTemplate.opsForSet().members(key);
  334. } catch (Exception e) {
  335. e.printStackTrace();
  336. return null;
  337. }
  338. }
  339. /**
  340. * 根据value从一个set中查询,是否存在
  341. * @param key 键
  342. * @param value 值
  343. * @return true 存在 false不存在
  344. */
  345. public boolean sHasKey(String key,Object value){
  346. try {
  347. return redisTemplate.opsForSet().isMember(key, value);
  348. } catch (Exception e) {
  349. e.printStackTrace();
  350. return false;
  351. }
  352. }
  353. /**
  354. * 将数据放入set缓存
  355. * @param key 键
  356. * @param values 值 可以是多个
  357. * @return 成功个数
  358. */
  359. public long sSet(String key, Object...values) {
  360. try {
  361. return redisTemplate.opsForSet().add(key, values);
  362. } catch (Exception e) {
  363. e.printStackTrace();
  364. return 0;
  365. }
  366. }
  367. /**
  368. * 将set数据放入缓存
  369. * @param key 键
  370. * @param time 时间(秒)
  371. * @param values 值 可以是多个
  372. * @return 成功个数
  373. */
  374. public long sSetAndTime(String key,long time,Object...values) {
  375. try {
  376. Long count = redisTemplate.opsForSet().add(key, values);
  377. if(time>0) expire(key, time);
  378. return count;
  379. } catch (Exception e) {
  380. e.printStackTrace();
  381. return 0;
  382. }
  383. }
  384. /**
  385. * 获取set缓存的长度
  386. * @param key 键
  387. * @return
  388. */
  389. public long sGetSetSize(String key){
  390. try {
  391. return redisTemplate.opsForSet().size(key);
  392. } catch (Exception e) {
  393. e.printStackTrace();
  394. return 0;
  395. }
  396. }
  397. /**
  398. * 移除值为value的
  399. * @param key 键
  400. * @param values 值 可以是多个
  401. * @return 移除的个数
  402. */
  403. public long setRemove(String key, Object ...values) {
  404. try {
  405. Long count = redisTemplate.opsForSet().remove(key, values);
  406. return count;
  407. } catch (Exception e) {
  408. e.printStackTrace();
  409. return 0;
  410. }
  411. }
  412. //===============================list=================================
  413. /**
  414. * 获取list缓存的内容
  415. * @param key 键
  416. * @param start 开始
  417. * @param end 结束 0 到 -1代表所有值
  418. * @return
  419. */
  420. public List<Object> lGet(String key, long start, long end){
  421. try {
  422. return redisTemplate.opsForList().range(key, start, end);
  423. } catch (Exception e) {
  424. e.printStackTrace();
  425. return null;
  426. }
  427. }
  428. /**
  429. * 获取list缓存的长度
  430. * @param key 键
  431. * @return
  432. */
  433. public long lGetListSize(String key){
  434. try {
  435. return redisTemplate.opsForList().size(key);
  436. } catch (Exception e) {
  437. e.printStackTrace();
  438. return 0;
  439. }
  440. }
  441. /**
  442. * 通过索引 获取list中的值
  443. * @param key 键
  444. * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  445. * @return
  446. */
  447. public Object lGetIndex(String key,long index){
  448. try {
  449. return redisTemplate.opsForList().index(key, index);
  450. } catch (Exception e) {
  451. e.printStackTrace();
  452. return null;
  453. }
  454. }
  455. /**
  456. * 将list放入缓存
  457. * @param key 键
  458. * @param value 值
  459. * @return
  460. */
  461. public boolean lSet(String key, Object value) {
  462. try {
  463. redisTemplate.opsForList().rightPush(key, value);
  464. return true;
  465. } catch (Exception e) {
  466. e.printStackTrace();
  467. return false;
  468. }
  469. }
  470. /**
  471. * 将list放入缓存
  472. * @param key 键
  473. * @param value 值
  474. * @param time 时间(秒)
  475. * @return
  476. */
  477. public boolean lSet(String key, Object value, long time) {
  478. try {
  479. redisTemplate.opsForList().rightPush(key, value);
  480. if (time > 0){
  481. expire(key, time);
  482. }
  483. return true;
  484. } catch (Exception e) {
  485. e.printStackTrace();
  486. return false;
  487. }
  488. }
  489. /**
  490. * 将list放入缓存
  491. * @param key 键
  492. * @param value 值
  493. * @return
  494. */
  495. public boolean lSet(String key, List<Object> value) {
  496. try {
  497. redisTemplate.opsForList().rightPushAll(key, value);
  498. return true;
  499. } catch (Exception e) {
  500. e.printStackTrace();
  501. return false;
  502. }
  503. }
  504. /**
  505. * 将list放入缓存
  506. * @param key 键
  507. * @param value 值
  508. * @param time 时间(秒)
  509. * @return
  510. */
  511. public boolean lSet(String key, List<Object> value, long time) {
  512. try {
  513. redisTemplate.opsForList().rightPushAll(key, value);
  514. if (time > 0){
  515. expire(key, time);
  516. }
  517. return true;
  518. } catch (Exception e) {
  519. e.printStackTrace();
  520. return false;
  521. }
  522. }
  523. /**
  524. * 根据索引修改list中的某条数据
  525. * @param key 键
  526. * @param index 索引
  527. * @param value 值
  528. * @return
  529. */
  530. public boolean lUpdateIndex(String key, long index,Object value) {
  531. try {
  532. redisTemplate.opsForList().set(key, index, value);
  533. return true;
  534. } catch (Exception e) {
  535. e.printStackTrace();
  536. return false;
  537. }
  538. }
  539. /**
  540. * 移除N个值为value
  541. * @param key 键
  542. * @param count 移除多少个
  543. * @param value 值
  544. * @return 移除的个数
  545. */
  546. public long lRemove(String key,long count,Object value) {
  547. try {
  548. Long remove = redisTemplate.opsForList().remove(key, count, value);
  549. return remove;
  550. } catch (Exception e) {
  551. e.printStackTrace();
  552. return 0;
  553. }
  554. }
  555. // ===============lock ==================
  556. /**
  557. * 加锁
  558. * @param key
  559. * @param time
  560. * @return
  561. */
  562. public Boolean tryLock(String key,long time) {
  563. boolean b = redisTemplate.opsForValue().setIfAbsent(key,"1");
  564. if(b){
  565. return redisTemplate.expire(key,time,TimeUnit.SECONDS);
  566. } else {
  567. return b;
  568. }
  569. }
  570. /**
  571. * 释放锁
  572. * @param key
  573. * @return
  574. */
  575. public void releaseLock(String key) {
  576. Object currentValue = redisTemplate.opsForValue().get(key);
  577. if (currentValue != null) {
  578. redisTemplate.delete(key);
  579. }
  580. }
  581. /**
  582. * 加锁
  583. * @param key
  584. * @param time
  585. * @return
  586. */
  587. public Boolean tryLock(String key,String requestId,long time) {
  588. boolean b = redisTemplate.opsForValue().setIfAbsent(key,requestId);
  589. if(b){
  590. return redisTemplate.expire(key,time,TimeUnit.SECONDS);
  591. } else {
  592. return b;
  593. }
  594. }
  595. /**
  596. * 释放锁
  597. * @param key
  598. * @return
  599. */
  600. public void releaseLock(String key,String requestId) {
  601. String currentValue = (String)redisTemplate.opsForValue().get(key);
  602. if (currentValue != null && requestId.equals(currentValue)) {
  603. redisTemplate.delete(key);
  604. }
  605. }
  606. public boolean zSetAdd(String key, Object value, long score) {
  607. try {
  608. boolean re = redisTemplate.opsForZSet().add(key, value, score);
  609. return re;
  610. } catch(Exception e) {
  611. e.printStackTrace();
  612. return false;
  613. }
  614. }
  615. public Set zSetRangeByScore(String key, double min, double max) {
  616. try {
  617. Set value = redisTemplate.opsForZSet().rangeByScore(key, min, max);
  618. return value;
  619. } catch(Exception e) {
  620. e.printStackTrace();
  621. return null;
  622. }
  623. }
  624. public Long zSetRemoveRangeByScore(String key, double min, double max) {
  625. try {
  626. Long value = redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
  627. return value;
  628. } catch(Exception e) {
  629. e.printStackTrace();
  630. return null;
  631. }
  632. }
  633. }