RedisUtil.java 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. package com.futu.course.common.utils;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.dao.DataAccessException;
  4. import org.springframework.data.redis.connection.RedisConnection;
  5. import org.springframework.data.redis.core.BoundListOperations;
  6. import org.springframework.data.redis.core.HashOperations;
  7. import org.springframework.data.redis.core.RedisCallback;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
  10. import org.springframework.data.redis.support.atomic.RedisAtomicLong;
  11. import org.springframework.stereotype.Component;
  12. import org.springframework.util.CollectionUtils;
  13. import java.util.*;
  14. import java.util.concurrent.TimeUnit;
  15. /**
  16. * redisTemplate封装
  17. */
  18. @Component
  19. public class RedisUtil {
  20. @Autowired
  21. private final RedisTemplate redisTemplate;
  22. //锁名称前缀
  23. public static final String LOCK_PREFIX = "redis_lock";
  24. //加锁失效时间,毫秒
  25. public static final int LOCK_EXPIRE = 10; // ms
  26. public static Integer workId=0;
  27. public static Integer dataId=0;
  28. public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
  29. this.redisTemplate = redisTemplate;
  30. }
  31. /**
  32. * redis发布消息
  33. *
  34. * @param channel
  35. * @param message
  36. */
  37. public void sendMessage(String channel, String message) {
  38. redisTemplate.convertAndSend(channel, message);
  39. }
  40. /**
  41. * 指定缓存失效时间
  42. *
  43. * @param key 键
  44. * @param time 时间(秒)
  45. * @return
  46. */
  47. public boolean expire(String key, long time, TimeUnit timeUnit) {
  48. try {
  49. if (time > 0) {
  50. redisTemplate.expire(key, time, timeUnit);
  51. }
  52. return true;
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. return false;
  56. }
  57. }
  58. /**
  59. * 根据key 获取过期时间
  60. *
  61. * @param key 键 不能为null
  62. * @return 时间(秒) 返回0代表为永久有效
  63. */
  64. public long getExpire(String key) {
  65. return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  66. }
  67. /**
  68. * 判断key是否存在
  69. *
  70. * @param key 键
  71. * @return true 存在 false不存在
  72. */
  73. public boolean hasKey(String key) {
  74. try {
  75. return redisTemplate.hasKey(key);
  76. } catch (Exception e) {
  77. e.printStackTrace();
  78. return false;
  79. }
  80. }
  81. /**
  82. * 删除缓存
  83. *
  84. * @param key 可以传一个值 或多个
  85. */
  86. @SuppressWarnings("unchecked")
  87. public void del(String... key) {
  88. if (key != null && key.length > 0) {
  89. if (key.length == 1) {
  90. redisTemplate.delete(key[0]);
  91. } else {
  92. redisTemplate.delete(CollectionUtils.arrayToList(key));
  93. }
  94. }
  95. }
  96. /**
  97. * 删除缓存
  98. *
  99. * @param keys 集合
  100. */
  101. public void del(Collection<String> keys) {
  102. redisTemplate.delete(keys);
  103. }
  104. //============================String=============================
  105. /**
  106. * 普通缓存获取
  107. *
  108. * @param key 键
  109. * @return 值
  110. */
  111. public Object get(String key) {
  112. return key == null ? null : redisTemplate.opsForValue().get(key);
  113. }
  114. /**
  115. * 普通缓存放入
  116. *
  117. * @param key 键
  118. * @param value 值
  119. * @return true成功 false失败
  120. */
  121. public boolean set(String key, Object value) {
  122. try {
  123. redisTemplate.opsForValue().set(key, value);
  124. return true;
  125. } catch (Exception e) {
  126. e.printStackTrace();
  127. return false;
  128. }
  129. }
  130. /**
  131. * 普通缓存放入并设置时间
  132. *
  133. * @param key 键
  134. * @param value 值
  135. * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
  136. * @return true成功 false 失败
  137. */
  138. public boolean set(String key, Object value, long time, TimeUnit timeUnit) {
  139. try {
  140. if (time > 0) {
  141. redisTemplate.opsForValue().set(key, value, time, timeUnit);
  142. } else {
  143. set(key, value);
  144. }
  145. return true;
  146. } catch (Exception e) {
  147. e.printStackTrace();
  148. return false;
  149. }
  150. }
  151. /**
  152. * 递增
  153. *
  154. * @param key 键
  155. * @param delta 要增加几(大于0)
  156. * @return
  157. */
  158. public long incr(String key, long delta) {
  159. if (delta < 0) {
  160. throw new RuntimeException("递增因子必须大于0");
  161. }
  162. return redisTemplate.opsForValue().increment(key, delta);
  163. }
  164. /**
  165. * 递减
  166. *
  167. * @param key 键
  168. * @param delta 要减少几(小于0)
  169. * @return
  170. */
  171. public long decr(String key, long delta) {
  172. if (delta < 0) {
  173. throw new RuntimeException("递减因子必须大于0");
  174. }
  175. return redisTemplate.opsForValue().decrement(key, delta);
  176. }
  177. //================================Map=================================
  178. /**
  179. * HashGet
  180. *
  181. * @param key 键 不能为null
  182. * @param item 项 不能为null
  183. * @return 值
  184. */
  185. public Object hget(String key, String item) {
  186. return redisTemplate.opsForHash().get(key, item);
  187. }
  188. /**
  189. * 获取hashKey对应的所有键值
  190. *
  191. * @param key 键
  192. * @return 对应的多个键值
  193. */
  194. public Map<Object, Object> hmget(String key) {
  195. return redisTemplate.opsForHash().entries(key);
  196. }
  197. /**
  198. * HashSet
  199. *
  200. * @param key 键
  201. * @param map 对应多个键值
  202. * @return true 成功 false 失败
  203. */
  204. public boolean hmset(String key, Map<String, Object> map) {
  205. try {
  206. redisTemplate.opsForHash().putAll(key, map);
  207. return true;
  208. } catch (Exception e) {
  209. e.printStackTrace();
  210. return false;
  211. }
  212. }
  213. /**
  214. * HashSet 并设置时间
  215. *
  216. * @param key 键
  217. * @param map 对应多个键值
  218. * @param time 时间(秒)
  219. * @return true成功 false失败
  220. */
  221. public boolean hmset(String key, Map<String, Object> map, long time, TimeUnit timeUnit) {
  222. try {
  223. redisTemplate.opsForHash().putAll(key, map);
  224. if (time > 0) {
  225. expire(key, time, timeUnit);
  226. }
  227. return true;
  228. } catch (Exception e) {
  229. e.printStackTrace();
  230. return false;
  231. }
  232. }
  233. /**
  234. * 向一张hash表中放入数据,如果不存在将创建
  235. *
  236. * @param key 键
  237. * @param item 项
  238. * @param value 值
  239. * @return true 成功 false失败
  240. */
  241. public boolean hset(String key, String item, Object value) {
  242. try {
  243. redisTemplate.opsForHash().put(key, item, value);
  244. return true;
  245. } catch (Exception e) {
  246. e.printStackTrace();
  247. return false;
  248. }
  249. }
  250. /**
  251. * 向一张hash表中放入数据,如果不存在将创建
  252. *
  253. * @param key 键
  254. * @param item 项
  255. * @param value 值
  256. * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  257. * @return true 成功 false失败
  258. */
  259. public boolean hset(String key, String item, Object value, long time, TimeUnit timeUnit) {
  260. try {
  261. redisTemplate.opsForHash().put(key, item, value);
  262. if (time > 0) {
  263. expire(key, time, timeUnit);
  264. }
  265. return true;
  266. } catch (Exception e) {
  267. e.printStackTrace();
  268. return false;
  269. }
  270. }
  271. /**
  272. * 删除hash表中的值
  273. *
  274. * @param key 键 不能为null
  275. * @param item 项 可以使多个 不能为null
  276. */
  277. public void hdel(String key, Object... item) {
  278. redisTemplate.opsForHash().delete(key, item);
  279. }
  280. /**
  281. * 判断hash表中是否有该项的值
  282. *
  283. * @param key 键 不能为null
  284. * @param item 项 不能为null
  285. * @return true 存在 false不存在
  286. */
  287. public boolean hHasKey(String key, String item) {
  288. return redisTemplate.opsForHash().hasKey(key, item);
  289. }
  290. /**
  291. * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  292. *
  293. * @param key 键
  294. * @param item 项
  295. * @param by 要增加几(大于0)
  296. * @return
  297. */
  298. public double hincr(String key, String item, double by) {
  299. return redisTemplate.opsForHash().increment(key, item, by);
  300. }
  301. /**
  302. * hash递减
  303. *
  304. * @param key 键
  305. * @param item 项
  306. * @param by 要减少记(小于0)
  307. * @return
  308. */
  309. public double hdecr(String key, String item, double by) {
  310. return redisTemplate.opsForHash().increment(key, item, -by);
  311. }
  312. //============================set=============================
  313. /**
  314. * 根据key获取Set中的所有值
  315. *
  316. * @param key 键
  317. * @return
  318. */
  319. public Set<Object> sGet(String key) {
  320. try {
  321. return redisTemplate.opsForSet().members(key);
  322. } catch (Exception e) {
  323. e.printStackTrace();
  324. return null;
  325. }
  326. }
  327. /**
  328. * 根据value从一个set中查询,是否存在
  329. *
  330. * @param key 键
  331. * @param value 值
  332. * @return true 存在 false不存在
  333. */
  334. public boolean sHasKey(String key, Object value) {
  335. try {
  336. return redisTemplate.opsForSet().isMember(key, value);
  337. } catch (Exception e) {
  338. e.printStackTrace();
  339. return false;
  340. }
  341. }
  342. /**
  343. * 将数据放入set缓存
  344. *
  345. * @param key 键
  346. * @param values 值 可以是多个
  347. * @return 成功个数
  348. */
  349. public long sSet(String key, Object... values) {
  350. try {
  351. return redisTemplate.opsForSet().add(key, values);
  352. } catch (Exception e) {
  353. e.printStackTrace();
  354. return 0;
  355. }
  356. }
  357. /**
  358. * 获得锁
  359. *
  360. * @param lock
  361. * @return
  362. */
  363. public boolean lock(String lock) {
  364. return (boolean) redisTemplate.execute((RedisCallback) connection -> {
  365. //获取时间毫秒值
  366. long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
  367. //获取锁
  368. Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());
  369. if (acquire) {
  370. return true;
  371. } else {
  372. byte[] bytes = connection.get(lock.getBytes());
  373. //非空判断
  374. if (Objects.nonNull(bytes) && bytes.length > 0) {
  375. long expireTime = Long.parseLong(new String(bytes));
  376. // 如果锁已经过期
  377. if (expireTime < System.currentTimeMillis()) {
  378. // 重新加锁,防止死锁
  379. byte[] set = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
  380. return Long.parseLong(new String(set)) < System.currentTimeMillis();
  381. }
  382. }
  383. }
  384. return false;
  385. });
  386. }
  387. /**
  388. * 获得锁
  389. *
  390. * @param lock
  391. * @return
  392. */
  393. public boolean lock(String lock,Long timeOut) {
  394. return (boolean) redisTemplate.execute((RedisCallback) connection -> {
  395. //获取时间毫秒值
  396. long expireAt = System.currentTimeMillis() + timeOut + 1;
  397. //获取锁
  398. Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());
  399. if (acquire) {
  400. return true;
  401. } else {
  402. byte[] bytes = connection.get(lock.getBytes());
  403. //非空判断
  404. if (Objects.nonNull(bytes) && bytes.length > 0) {
  405. long expireTime = Long.parseLong(new String(bytes));
  406. // 如果锁已经过期
  407. if (expireTime < System.currentTimeMillis()) {
  408. // 重新加锁,防止死锁
  409. byte[] set = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
  410. return Long.parseLong(new String(set)) < System.currentTimeMillis();
  411. }
  412. }
  413. }
  414. return false;
  415. });
  416. }
  417. /**
  418. * 删除锁
  419. *
  420. * @param key
  421. */
  422. public void deleteLock(String key) {
  423. redisTemplate.delete(key);
  424. }
  425. /**
  426. * 加锁,⽆阻塞
  427. * <p>
  428. * 锁
  429. *
  430. * @param key 请求标识
  431. * @param userId 超期时间
  432. * @param expireTime 上锁时间,单位TimeUnit.SECONDS
  433. * @param timeout 等待时间,单位TimeUnit.SECONDS
  434. * @return
  435. */
  436. public Boolean lock(String key, long expireTime, Long userId, long timeout) {
  437. Long start = System.currentTimeMillis();
  438. //在⼀定时间内获取锁,超时则返回错误
  439. //
  440. for (; ; ) {
  441. //,则证明获取锁成功
  442. //Set
  443. // OK
  444. Boolean ret = redisTemplate.opsForValue().setIfAbsent(key, userId, expireTime, TimeUnit.SECONDS);
  445. if (ret != null && ret) {
  446. return true;
  447. }
  448. // 否则循环等待,在
  449. // 时间内仍未获取到锁,则获取失败
  450. long end = System.currentTimeMillis() - start;
  451. if (end >= timeout * 1000) {
  452. return false;
  453. }
  454. }
  455. }
  456. public Boolean lock(String key, long expireTime, Long userId) {
  457. Boolean ret = redisTemplate.opsForValue().setIfAbsent(key, userId, expireTime, TimeUnit.SECONDS);
  458. return ret != null && ret;
  459. }
  460. public Boolean unlock(String key, Long userId) {
  461. Object o = redisTemplate.opsForValue().get(key);
  462. if(userId.equals(o)){
  463. return redisTemplate.delete(key);
  464. }else{
  465. return false;
  466. }
  467. }
  468. /**
  469. * 将set数据放入缓存
  470. *
  471. * @param key 键
  472. * @param time 时间(秒)
  473. * @param values 值 可以是多个
  474. * @return 成功个数
  475. */
  476. public long sSetAndTime(String key, long time, TimeUnit timeUnit, Object... values) {
  477. try {
  478. Long count = redisTemplate.opsForSet().add(key, values);
  479. if (time > 0) {
  480. expire(key, time, timeUnit);
  481. }
  482. return count;
  483. } catch (Exception e) {
  484. e.printStackTrace();
  485. return 0;
  486. }
  487. }
  488. /**
  489. * 获取set缓存的长度
  490. *
  491. * @param key 键
  492. * @return
  493. */
  494. public long sGetSetSize(String key) {
  495. try {
  496. return redisTemplate.opsForSet().size(key);
  497. } catch (Exception e) {
  498. e.printStackTrace();
  499. return 0;
  500. }
  501. }
  502. /**
  503. * 移除值为value的
  504. *
  505. * @param key 键
  506. * @param values 值 可以是多个
  507. * @return 移除的个数
  508. */
  509. public long setRemove(String key, Object... values) {
  510. try {
  511. Long count = redisTemplate.opsForSet().remove(key, values);
  512. return count;
  513. } catch (Exception e) {
  514. e.printStackTrace();
  515. return 0;
  516. }
  517. }
  518. //===============================list=================================
  519. /**
  520. * 获取list缓存的内容
  521. *
  522. * @param key 键
  523. * @param start 开始
  524. * @param end 结束 0 到 -1代表所有值
  525. * @return
  526. */
  527. public List<Object> listGet(String key, long start, long end) {
  528. try {
  529. return redisTemplate.opsForList().range(key, start, end);
  530. } catch (Exception e) {
  531. e.printStackTrace();
  532. return null;
  533. }
  534. }
  535. /**
  536. * 弹出对象
  537. * @param key
  538. * @return
  539. */
  540. public Object popLeftList(String key){
  541. return redisTemplate.opsForList().leftPop(key);
  542. }
  543. /**
  544. * 获取list缓存的长度
  545. *
  546. * @param key 键
  547. * @return
  548. */
  549. public long listSize(String key) {
  550. try {
  551. return redisTemplate.opsForList().size(key);
  552. } catch (Exception e) {
  553. e.printStackTrace();
  554. return 0;
  555. }
  556. }
  557. /**
  558. * 通过索引 获取list中的值
  559. *
  560. * @param key 键
  561. * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  562. * @return
  563. */
  564. public Object listGetIndex(String key, long index) {
  565. try {
  566. return redisTemplate.opsForList().index(key, index);
  567. } catch (Exception e) {
  568. e.printStackTrace();
  569. return null;
  570. }
  571. }
  572. /**
  573. * 将list放入缓存
  574. *
  575. * @param key 键
  576. * @param value 值
  577. * @return
  578. */
  579. public boolean listSet(String key, Object value) {
  580. try {
  581. redisTemplate.opsForList().rightPush(key, value);
  582. return true;
  583. } catch (Exception e) {
  584. e.printStackTrace();
  585. return false;
  586. }
  587. }
  588. public void listTrim(String key, long start,long end) {
  589. try {
  590. redisTemplate.opsForList().trim(key,start,end);
  591. } catch (Exception e) {
  592. e.printStackTrace();
  593. }
  594. }
  595. /**
  596. * 将list放入缓存
  597. *
  598. * @param key 键
  599. * @param value 值
  600. * @param time 时间(秒)
  601. * @return
  602. */
  603. public boolean listSet(String key, Object value, long time, TimeUnit timeUnit) {
  604. try {
  605. redisTemplate.opsForList().rightPush(key, value);
  606. if (time > 0) {
  607. expire(key, time, timeUnit);
  608. }
  609. return true;
  610. } catch (Exception e) {
  611. e.printStackTrace();
  612. return false;
  613. }
  614. }
  615. /**
  616. * 将list放入缓存
  617. *
  618. * @param key 键
  619. * @param value 值
  620. * @return
  621. */
  622. public boolean listSet(String key, List<Object> value) {
  623. try {
  624. redisTemplate.opsForList().rightPushAll(key, value);
  625. return true;
  626. } catch (Exception e) {
  627. e.printStackTrace();
  628. return false;
  629. }
  630. }
  631. /**
  632. * list大小
  633. * @param key
  634. * @return
  635. */
  636. public Long getListSize(String key){
  637. return redisTemplate.opsForList().size(key);
  638. }
  639. /**
  640. * 将list放入缓存
  641. *
  642. * @param key 键
  643. * @param value 值
  644. * @param time 时间(秒)
  645. * @return
  646. */
  647. public boolean listSet(String key, List<Object> value, long time, TimeUnit timeUnit) {
  648. try {
  649. redisTemplate.opsForList().rightPushAll(key, value);
  650. if (time > 0) {
  651. expire(key, time, timeUnit);
  652. }
  653. return true;
  654. } catch (Exception e) {
  655. e.printStackTrace();
  656. return false;
  657. }
  658. }
  659. /**
  660. * 根据索引修改list中的某条数据
  661. *
  662. * @param key 键
  663. * @param index 索引
  664. * @param value 值
  665. * @return
  666. */
  667. public boolean listUpdateIndex(String key, long index, Object value) {
  668. try {
  669. redisTemplate.opsForList().set(key, index, value);
  670. return true;
  671. } catch (Exception e) {
  672. e.printStackTrace();
  673. return false;
  674. }
  675. }
  676. /**
  677. * 移除N个值为value
  678. *
  679. * @param key 键
  680. * @param count 移除多少个
  681. * @param value 值
  682. * @return 移除的个数
  683. */
  684. public long listRemove(String key, long count, Object value) {
  685. try {
  686. Long remove = redisTemplate.opsForList().remove(key, count, value);
  687. return remove;
  688. } catch (Exception e) {
  689. e.printStackTrace();
  690. return 0;
  691. }
  692. }
  693. /**
  694. * 模糊查询获取key值
  695. *
  696. * @param pattern
  697. * @return
  698. */
  699. public Set keys(String pattern) {
  700. return redisTemplate.keys(pattern);
  701. }
  702. /**
  703. * 使用Redis的消息队列
  704. *
  705. * @param channel
  706. * @param message 消息内容
  707. */
  708. public void convertAndSend(String channel, Object message) {
  709. redisTemplate.convertAndSend(channel, message);
  710. }
  711. //=========BoundListOperations 用法 start============
  712. /**
  713. * 将数据添加到Redis的list中(从右边添加)
  714. *
  715. * @param listKey
  716. * @param time 过期时间
  717. * @param values 待添加的数据
  718. */
  719. public void addToListRight(String listKey, long time, Object... values) {
  720. //绑定操作
  721. BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
  722. //插入数据
  723. boundValueOperations.rightPushAll(values);
  724. //设置过期时间
  725. boundValueOperations.expire(time, TimeUnit.SECONDS);
  726. }
  727. /**
  728. * 根据起始结束序号遍历Redis中的list
  729. *
  730. * @param listKey
  731. * @param start 起始序号
  732. * @param end 结束序号
  733. * @return
  734. */
  735. public List<Object> rangeList(String listKey, long start, long end) {
  736. //绑定操作
  737. BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
  738. //查询数据
  739. return boundValueOperations.range(start, end);
  740. }
  741. /**
  742. * 弹出右边的值 --- 并且移除这个值
  743. *
  744. * @param listKey
  745. */
  746. public Object rifhtPop(String listKey) {
  747. //绑定操作
  748. BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
  749. return boundValueOperations.rightPop();
  750. }
  751. /**
  752. * @param key
  753. * @return
  754. */
  755. public Long getIncr(String key) {
  756. RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
  757. Long increment = entityIdCounter.getAndIncrement();
  758. return increment;
  759. }
  760. /**
  761. * @return
  762. */
  763. public synchronized Integer getSequenceId() {
  764. String key = "sms_sequence_id";
  765. RedisAtomicInteger idCount = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
  766. int sequenceId = idCount.getAndIncrement();
  767. if (sequenceId <= 1000 || sequenceId >= 1000000000) {
  768. idCount.set(1000);
  769. sequenceId = idCount.getAndIncrement();
  770. return sequenceId;
  771. }
  772. return sequenceId;
  773. }
  774. public void setCount(String key ,int initValue){
  775. RedisAtomicInteger idCount = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
  776. idCount.set(initValue);
  777. }
  778. /**
  779. * @return
  780. */
  781. public Integer getCount(String key) {
  782. RedisAtomicInteger idCount = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
  783. int count = idCount.getAndIncrement();
  784. if (count ==Integer.MAX_VALUE-1) {
  785. idCount.set(0);
  786. count = idCount.getAndIncrement();
  787. return count;
  788. }
  789. return count;
  790. }
  791. public Integer getStartCount(String key) {
  792. RedisAtomicInteger idCount = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
  793. int count = idCount.getAndIncrement();
  794. if(count<=1){
  795. this.expire(key, CacheKey.DAY1,TimeUnit.DAYS);
  796. }
  797. if (count ==Integer.MAX_VALUE-1) {
  798. idCount.set(0);
  799. count = idCount.getAndIncrement();
  800. return count;
  801. }
  802. return count;
  803. }
  804. public String getStartNum(Integer num){
  805. String str=num.toString();
  806. int len=str.length();
  807. if(str.length()<5){
  808. StringBuilder sb = new StringBuilder();
  809. for(int i=0;i<5-len;i++){
  810. sb.append("0");
  811. }
  812. sb.append(str);
  813. return sb.toString();
  814. }
  815. return str;
  816. }
  817. public String getStartNum(String key){
  818. Integer num=getStartCount(key);
  819. String str=num.toString();
  820. int len=str.length();
  821. if(str.length()<5){
  822. StringBuilder sb = new StringBuilder();
  823. for(int i=0;i<5-len;i++){
  824. sb.append("0");
  825. }
  826. sb.append(str);
  827. return sb.toString();
  828. }
  829. return str;
  830. }
  831. public synchronized Integer getSequenceNumber3(String key) {
  832. RedisAtomicInteger idCount = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
  833. int sequenceId = idCount.getAndIncrement();
  834. if (sequenceId < 0 || sequenceId >= Integer.MAX_VALUE) {
  835. idCount.set(0);
  836. sequenceId = idCount.getAndIncrement();
  837. return sequenceId;
  838. }
  839. return sequenceId;
  840. }
  841. public synchronized Integer getWorkId(String key) {
  842. RedisAtomicInteger idCount = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
  843. int sequenceId = idCount.getAndIncrement();
  844. if (sequenceId < 0 || sequenceId >= 31) {
  845. idCount.set(0);
  846. sequenceId = idCount.getAndIncrement();
  847. return sequenceId;
  848. }
  849. return sequenceId;
  850. }
  851. /**
  852. * 14 * @Description: 初始化自增长值
  853. * 15 * @param key key
  854. * 16 * @param value 当前值
  855. * 17
  856. */
  857. public void setIncr(String key, int value) {
  858. RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
  859. counter.set(value);
  860. }
  861. /**
  862. * 14 * @Description: 初始化自增长值
  863. * 15 * @param key key
  864. * 16 * @param value 当前值
  865. * 17
  866. */
  867. public void setInteger(String key, int value) {
  868. RedisAtomicInteger counter = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
  869. counter.set(value);
  870. }
  871. /**
  872. * 保存到hash
  873. * @param key
  874. * @param hashKey
  875. * @param value
  876. */
  877. public void setHashMap(String key,Object hashKey,Object value){
  878. redisTemplate.opsForHash().put(key,hashKey,value);
  879. }
  880. /**
  881. * 获取hashvalue
  882. * @param key
  883. * @param hashKey
  884. * @return
  885. */
  886. public Object getHashValue(String key,Object hashKey){
  887. return redisTemplate.opsForHash().get(key,hashKey);
  888. }
  889. /**
  890. * 删除hash中单个对象
  891. * @param key
  892. * @param hashKey
  893. */
  894. public void remove(String key,Object hashKey){
  895. redisTemplate.opsForHash().delete(key,hashKey);
  896. }
  897. /**
  898. * 获取redisTemplate
  899. * @return
  900. */
  901. public RedisTemplate getRedisTemplate(){
  902. return redisTemplate;
  903. }
  904. /**
  905. * 存储数据或修改数据
  906. *
  907. * @param modelMap
  908. * @param mapName
  909. */
  910. public void setMap(String mapName, Map<String, Object> modelMap) {
  911. HashOperations<String, Object, Object> hps = redisTemplate.opsForHash();
  912. hps.putAll(mapName, modelMap);
  913. }
  914. /**
  915. * 获取数据Map
  916. *
  917. * @param mapName
  918. * @return
  919. */
  920. public Map<Object, Object> getMapValue(String mapName) {
  921. HashOperations<String, Object, Object> hps = this.redisTemplate.opsForHash();
  922. return hps.entries(mapName);
  923. }
  924. /**
  925. * 获取数据Map size
  926. *
  927. * @param mapName
  928. * @return
  929. */
  930. public int getMapSize(String mapName) {
  931. HashOperations<String, Object, Object> hps = this.redisTemplate.opsForHash();
  932. return hps.entries(mapName).size();
  933. }
  934. /**
  935. * 获取数据value
  936. *
  937. * @param mapName
  938. * @param hashKey
  939. * @return
  940. */
  941. public Object getValue(String mapName, String hashKey) {
  942. HashOperations<String, Object, Object> hps = this.redisTemplate.opsForHash();
  943. return hps.get(mapName, hashKey);
  944. }
  945. /**
  946. * 批量删除缓存数据
  947. *
  948. * @param keys
  949. */
  950. public long deleteData(String key,Object ...keys) {
  951. // 执行批量删除操作时先序列化template
  952. long b= redisTemplate.opsForHash().delete(key,keys);
  953. return b;
  954. }
  955. private void batchCacheMarketInfo(List<Object > dataList, long expire) {
  956. //使用pipeline方式
  957. redisTemplate.executePipelined(new RedisCallback<List<Object>>() {
  958. @Override
  959. public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
  960. for (Object marketInfo : dataList) {
  961. String key = "";
  962. byte[] rawKey = redisTemplate.getKeySerializer().serialize(key);
  963. connection.setEx(rawKey, expire, redisTemplate.getValueSerializer().serialize(marketInfo));
  964. }
  965. return null;
  966. }
  967. });
  968. }
  969. //=========BoundListOperations 用法 End============
  970. }