7.Spring Boot 中使用 Redis 数据库,Redis 分布式锁

2019年11月05日 09:40 · 阅读(306) ·

目标

在 Spring Boot 项目中设置,获取 Redis 值

前提条件

Redis 安装、使用

开发环境

名称 版本
操作系统 Windows 10 X64
JDK JDK1.8(jdk-8u151-windows-x64)
IntelliJ IDEA IntelliJ IDEA 2018.3
Maven Maven 3.6.0
Redis Redis-x64-3.2.100
RedisDesktopManager 0.8.8.384

说明

本文代码基于 6.Mybatisplus 代码生成器 的基础上进行修改

test-invoice-contract

添加接口

TRbtTestConsumer

  1. package com.test.invoice.service.consumer;
  2. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  3. import com.test.invoice.model.TRbtUserEntity;
  4. import com.test.invoice.service.hystrix.NotBreakerConfiguration;
  5. import com.test.invoice.vo.LoginRequestVO;
  6. import com.test.invoice.vo.ResponseVO;
  7. import org.springframework.cloud.openfeign.FeignClient;
  8. import org.springframework.web.bind.annotation.*;
  9. import com.test.invoice.data.TRbtTestData;
  10. import com.test.invoice.data.TRbtTestDataParam;
  11. import com.test.invoice.service.hystrix.TRbtTestHystrix;
  12. /**
  13. * Feign-api 接口定义——TRbtTestConsumer
  14. *
  15. * @author:
  16. * @version:
  17. * @date: 2019-08-08 14:45
  18. */
  19. //@FeignClient(value = "service-producer")
  20. //modify by v_hwhao 20190828 加入熔断处理
  21. //@FeignClient(value = "service-producer",fallback = TRbtTestHystrix.class)
  22. //modify by v_hwhao 20190927 - 不进入熔断,直接抛出异常
  23. @FeignClient(value = "service-producer",configuration = NotBreakerConfiguration.class)
  24. public interface TRbtTestConsumer {
  25. @PostMapping("/Test/RedisTest")
  26. ResponseVO<String> RedisTest();
  27. }

TRbtTestHystrix

  1. package com.test.invoice.service.hystrix;
  2. import com.test.invoice.data.TRbtTestData;
  3. import com.test.invoice.data.TRbtTestDataParam;
  4. import com.test.invoice.enums.ResponseCode;
  5. import com.test.invoice.model.TRbtUserEntity;
  6. import com.test.invoice.service.consumer.TRbtTestConsumer;
  7. import com.test.invoice.vo.LoginRequestVO;
  8. import com.test.invoice.vo.ResponseVO;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.web.bind.annotation.RequestBody;
  11. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  12. import org.springframework.web.bind.annotation.*;
  13. /**
  14. * TRbtTestHystrix - 熔断处理类
  15. *
  16. * @author:
  17. * @version:
  18. * @date: 2019-08-28 11:50
  19. */
  20. @Component
  21. public class TRbtTestHystrix implements TRbtTestConsumer {
  22. ResponseVO<String> resultString = new ResponseVO<>(ResponseCode.SYSTEM_EXCEPTION_HYSTRIX);
  23. @Override
  24. public ResponseVO<String> RedisTest(){
  25. return resultString;
  26. }
  27. }

test-invoice-service

pom.xml

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

application-dev.yml

  1. spring:
  2. #redis集群配置
  3. redis:
  4. # Redis服务器连接密码(默认为空)
  5. password:
  6. databsse: 1
  7. host: localhost #127.0.0.1,10.41.93.42
  8. port: 6379
  9. jedis:
  10. select: 1
  11. pool:
  12. # 连接池最大连接数(使用负值表示没有限制)
  13. max-active: 5000
  14. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  15. max-wait: -1s
  16. # 连接池中的最大空闲连接
  17. max-idle: 30
  18. # 连接池中的最小空闲连接
  19. min-idle: 5
  20. # 连接超时时间(毫秒)
  21. commandTimeout: 50000

RedisConfig

  1. package com.test.invoice.config;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.PropertyAccessor;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.data.redis.connection.RedisConnectionFactory;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.data.redis.core.StringRedisTemplate;
  10. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  11. import org.springframework.data.redis.serializer.StringRedisSerializer;
  12. @Configuration
  13. public class RedisConfig{
  14. /**
  15. * 对存取的字符串进行一个json格式的系列化初始配置
  16. *
  17. * @param factory
  18. * @return
  19. */
  20. @Bean
  21. public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
  22. StringRedisTemplate template = new StringRedisTemplate(factory);
  23. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  24. ObjectMapper objectMapper = new ObjectMapper();
  25. objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  26. objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  27. jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
  28. // 设置key和value的序列化规则
  29. template.setKeySerializer(new StringRedisSerializer());
  30. template.setValueSerializer(jackson2JsonRedisSerializer);
  31. template.afterPropertiesSet();
  32. return template;
  33. }
  34. @Bean
  35. public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
  36. StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
  37. stringRedisTemplate.setConnectionFactory(factory);
  38. return stringRedisTemplate;
  39. }
  40. }

RedisUtil

  1. package com.test.invoice.util;
  2. import java.util.Collection;
  3. import java.util.Collections;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Set;
  7. import java.util.concurrent.TimeUnit;
  8. import javax.annotation.Resource;
  9. import org.springframework.data.redis.core.RedisTemplate;
  10. import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
  11. import org.springframework.data.redis.core.script.DefaultRedisScript;
  12. import org.springframework.data.redis.core.script.RedisScript;
  13. import org.springframework.stereotype.Component;
  14. /**
  15. * redis 操作工具类
  16. */
  17. @Component
  18. public class RedisUtil {
  19. private static final Long SUCCESS = 1L;
  20. @Resource
  21. private RedisTemplate<Object, Object> redisTemplate;
  22. public RedisTemplate<Object, Object> getInstance() {
  23. return redisTemplate;
  24. }
  25. /***
  26. * 判断是否有Key
  27. * @param key
  28. * @return
  29. */
  30. public boolean exists(String key) {
  31. return redisTemplate.hasKey(key);
  32. }
  33. /**
  34. * 设置 String 类型 key-value
  35. *
  36. * @param key
  37. * @param value
  38. */
  39. public void set(String key, String value) {
  40. redisTemplate.opsForValue().set(key, value);
  41. }
  42. /**
  43. * 设置 int 类型 key-value
  44. *
  45. * @param key
  46. * @param value
  47. */
  48. public void set(String key, Integer value) {
  49. redisTemplate.opsForValue().set(key, value);
  50. }
  51. /**
  52. * 获取 String 类型 key-value
  53. *
  54. * @param key
  55. * @return
  56. */
  57. public String get(String key) {
  58. return (String) redisTemplate.opsForValue().get(key);
  59. }
  60. /**
  61. * 获取 Long 类型 key-value
  62. *
  63. * @param key
  64. * @return
  65. */
  66. public Integer getInt(String key) {
  67. return (Integer) redisTemplate.opsForValue().get(key);
  68. }
  69. /**
  70. * 设置 String 类型 key-value 并添加过期时间 (毫秒单位)
  71. *
  72. * @param key
  73. * @param value
  74. * @param time 过期时间,毫秒单位
  75. */
  76. public void setForTimeMS(String key, String value, long time) {
  77. redisTemplate.opsForValue().set(key, value, time, TimeUnit.MILLISECONDS);
  78. }
  79. /**
  80. * 设置 String 类型 key-value 并添加过期时间 (毫秒单位)
  81. *
  82. * @param key
  83. * @param value
  84. * @param time 过期时间,毫秒单位
  85. */
  86. public void setForTimeSec(String key, String value, long time) {
  87. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  88. }
  89. /**
  90. * 设置 String 类型 key-value 并添加过期时间 (分钟单位)
  91. *
  92. * @param key
  93. * @param value
  94. * @param time 过期时间,分钟单位
  95. */
  96. public void setForTimeMIN(String key, String value, long time) {
  97. redisTemplate.opsForValue().set(key, value, time, TimeUnit.MINUTES);
  98. }
  99. /**
  100. * 设置 String 类型 key-value 并添加过期时间 (分钟单位)
  101. *
  102. * @param key
  103. * @param value
  104. * @param time 过期时间,分钟单位
  105. */
  106. public void setForTimeCustom(String key, String value, long time, TimeUnit type) {
  107. redisTemplate.opsForValue().set(key, value, time, type);
  108. }
  109. /**
  110. * 如果 key 存在则覆盖,并返回旧值. 如果不存在,返回null 并添加
  111. *
  112. * @param key
  113. * @param value
  114. * @return
  115. */
  116. public String getAndSet(String key, String value) {
  117. return (String) redisTemplate.opsForValue().getAndSet(key, value);
  118. }
  119. /**
  120. * 批量添加 key-value (重复的键会覆盖)
  121. *
  122. * @param keyAndValue
  123. */
  124. public void batchSet(Map<String, String> keyAndValue) {
  125. redisTemplate.opsForValue().multiSet(keyAndValue);
  126. }
  127. /**
  128. * 批量添加 key-value 只有在键不存在时,才添加 map 中只要有一个key存在,则全部不添加
  129. *
  130. * @param keyAndValue
  131. */
  132. public void batchSetIfAbsent(Map<String, String> keyAndValue) {
  133. redisTemplate.opsForValue().multiSetIfAbsent(keyAndValue);
  134. }
  135. /**
  136. * 对一个 key-value 的值进行加减操作, 如果该 key 不存在 将创建一个key 并赋值该 number 如果 key 存在,但 value 不是长整型 ,将报错
  137. *
  138. * @param key
  139. * @param number
  140. */
  141. public Long increment(String key, long number) {
  142. return redisTemplate.opsForValue().increment(key, number);
  143. }
  144. /**
  145. * 对一个 key-value 的值进行加减操作, 如果该 key 不存在 将创建一个key 并赋值该 number 如果 key 存在,但 value 不是 纯数字 ,将报错
  146. *
  147. * @param key
  148. * @param number
  149. */
  150. public Double increment(String key, double number) {
  151. return redisTemplate.opsForValue().increment(key, number);
  152. }
  153. /**
  154. * 给指定 hash 的 hashkey 做增减操作
  155. *
  156. * @param key
  157. * @param hashKey
  158. * @param number
  159. * @return
  160. */
  161. public Long increment(String key, String hashKey, long number) {
  162. return redisTemplate.opsForHash().increment(key, hashKey, number);
  163. }
  164. /**
  165. * 给指定 hash 的 hashkey 做增减操作
  166. *
  167. * @param key
  168. * @param hashKey
  169. * @param number
  170. * @return
  171. */
  172. public Double increment(String key, String hashKey, Double number) {
  173. return redisTemplate.opsForHash().increment(key, hashKey, number);
  174. }
  175. /**
  176. * 给一个指定的 key 值附加过期时间
  177. *
  178. * @param key
  179. * @param time
  180. * @param type
  181. * @return
  182. */
  183. public boolean expire(String key, long time, TimeUnit type) {
  184. return redisTemplate.boundValueOps(key).expire(time, type);
  185. }
  186. /**
  187. * 移除指定key 的过期时间
  188. *
  189. * @param key
  190. * @return
  191. */
  192. public boolean persist(String key) {
  193. return redisTemplate.boundValueOps(key).persist();
  194. }
  195. /**
  196. * 获取指定key 的过期时间
  197. *
  198. * @param key
  199. * @return
  200. */
  201. public Long getExpire(String key) {
  202. return redisTemplate.boundValueOps(key).getExpire();
  203. }
  204. /**
  205. * 修改 key
  206. *
  207. * @param key
  208. * @return
  209. */
  210. public void rename(String key, String newKey) {
  211. redisTemplate.boundValueOps(key).rename(newKey);
  212. }
  213. /**
  214. * 删除 key-value
  215. *
  216. * @param key
  217. * @return
  218. */
  219. public boolean delete(String key) {
  220. return redisTemplate.delete(key);
  221. }
  222. /**
  223. * 删除指定 hash 的 HashKey
  224. *
  225. * @param key
  226. * @param hashKeys
  227. * @return 删除成功的 数量
  228. */
  229. public Long delete(String key, String... hashKeys) {
  230. return redisTemplate.opsForHash().delete(key, hashKeys);
  231. }
  232. //hash操作
  233. /**
  234. * 添加 Hash 键值对
  235. *
  236. * @param key
  237. * @param hashKey
  238. * @param value
  239. */
  240. public void put(String key, String hashKey, String value) {
  241. redisTemplate.opsForHash().put(key, hashKey, value);
  242. }
  243. /**
  244. * 批量添加 hash 的 键值对 有则覆盖,没有则添加
  245. *
  246. * @param key
  247. * @param map
  248. */
  249. public void putAll(String key, Map<String, String> map) {
  250. redisTemplate.opsForHash().putAll(key, map);
  251. }
  252. /**
  253. * 添加 hash 键值对. 不存在的时候才添加
  254. *
  255. * @param key
  256. * @param hashKey
  257. * @param value
  258. * @return
  259. */
  260. public boolean putIfAbsent(String key, String hashKey, String value) {
  261. return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
  262. }
  263. /**
  264. * 获取指定 key 下的 hashkey
  265. *
  266. * @param key
  267. * @param hashKey
  268. * @return
  269. */
  270. public Object getHashKey(String key, String hashKey) {
  271. return redisTemplate.opsForHash().get(key, hashKey);
  272. }
  273. /**
  274. * 获取 key 下的 所有 hashkey 和 value
  275. *
  276. * @param key
  277. * @return
  278. */
  279. public Map<Object, Object> getHashEntries(String key) {
  280. return redisTemplate.opsForHash().entries(key);
  281. }
  282. /**
  283. * 验证指定 key 下 有没有指定的 hashkey
  284. *
  285. * @param key
  286. * @param hashKey
  287. * @return
  288. */
  289. public boolean hashKey(String key, String hashKey) {
  290. return redisTemplate.opsForHash().hasKey(key, hashKey);
  291. }
  292. /**
  293. * 获取 key 下的 所有 hashkey 字段名
  294. *
  295. * @param key
  296. * @return
  297. */
  298. public Set<Object> hashKeys(String key) {
  299. return redisTemplate.opsForHash().keys(key);
  300. }
  301. /**
  302. * 获取指定 hash 下面的 键值对 数量
  303. *
  304. * @param key
  305. * @return
  306. */
  307. public Long hashSize(String key) {
  308. return redisTemplate.opsForHash().size(key);
  309. }
  310. //List 操作
  311. /**
  312. * 指定 list 从左入栈
  313. *
  314. * @param key
  315. * @return 当前队列的长度
  316. */
  317. public Long leftPush(String key, Object value) {
  318. return redisTemplate.opsForList().leftPush(key, value);
  319. }
  320. /**
  321. * 指定 list 从左出栈 如果列表没有元素
  322. *
  323. * @param key
  324. * @return 出栈的值
  325. */
  326. public Object leftPopNoWait(String key) {
  327. return redisTemplate.opsForList().leftPop(key);
  328. }
  329. /**
  330. * 指定 list 从左出栈,会堵塞到列表一直有元素或者超时为止
  331. *
  332. * @param key
  333. * @return 出栈的值
  334. */
  335. public Object leftPop(String key) {
  336. return redisTemplate.opsForList().leftPop(key, 0, TimeUnit.MILLISECONDS);
  337. }
  338. /**
  339. * 清空key并将list从左入栈
  340. *
  341. * @param key
  342. * @param values
  343. * @return
  344. */
  345. public Long clearAndLeftPushAll(String key, Collection<Object> values) {
  346. DefaultRedisScript<Long> script = new DefaultRedisScript<>();
  347. script.setScriptText(
  348. "redis.call('del', KEYS[1])\nfor i, value in ipairs(ARGV) do\n redis.call('lpush', KEYS[1], value)\nend\nreturn redis.call('llen', KEYS[1])");
  349. script.setResultType(Long.class);
  350. return redisTemplate.execute(script, Collections.singletonList(key), values.toArray());
  351. }
  352. /**
  353. * 从左边依次入栈 导入顺序按照 Collection 顺序 如: a b c => c b a
  354. *
  355. * @param key
  356. * @param values
  357. * @return
  358. */
  359. public Long leftPushAll(String key, Collection<Object> values) {
  360. return redisTemplate.opsForList().leftPushAll(key, values);
  361. }
  362. /**
  363. * 指定 list 从右入栈
  364. *
  365. * @param key
  366. * @return 当前队列的长度
  367. */
  368. public Long rightPush(String key, Object value) {
  369. return redisTemplate.opsForList().rightPush(key, value);
  370. }
  371. /**
  372. * 指定 list 从右出栈 如果列表没有元素,会堵塞到列表一直有元素或者超时为止
  373. *
  374. * @param key
  375. * @return 出栈的值
  376. */
  377. public Object rightPopNoWait(String key) {
  378. return redisTemplate.opsForList().rightPop(key);
  379. }
  380. /**
  381. * 指定 list 从右出栈
  382. *
  383. * @param key
  384. * @return 出栈的值
  385. */
  386. public Object rightPop(String key) {
  387. return redisTemplate.opsForList().rightPop(key, 0, TimeUnit.MILLISECONDS);
  388. }
  389. /**
  390. * 从右边依次入栈 导入顺序按照 Collection 顺序 如: a b c => a b c
  391. *
  392. * @param key
  393. * @param values
  394. * @return
  395. */
  396. public Long rightPushAll(String key, Collection<Object> values) {
  397. return redisTemplate.opsForList().rightPushAll(key, values);
  398. }
  399. /**
  400. * 清空key并将list从右入栈
  401. *
  402. * @param key
  403. * @param values
  404. * @return
  405. */
  406. public Long clearAndRightPushAll(String key, Collection<Object> values) {
  407. DefaultRedisScript<Long> script = new DefaultRedisScript<>();
  408. script.setScriptText(
  409. "redis.call('del', KEYS[1])\nfor i, value in ipairs(ARGV) do\n redis.call('rpush', KEYS[1], value)\nend\nreturn redis.call('llen', KEYS[1])");
  410. script.setResultType(Long.class);
  411. return redisTemplate.execute(script, Collections.singletonList(key), values.toArray());
  412. }
  413. /**
  414. * 根据下标获取值
  415. *
  416. * @param key
  417. * @param index
  418. * @return
  419. */
  420. public Object popIndex(String key, long index) {
  421. return redisTemplate.opsForList().index(key, index);
  422. }
  423. /**
  424. * 获取列表指定长度
  425. *
  426. * @param key
  427. * @param index
  428. * @return
  429. */
  430. public Long listSize(String key, long index) {
  431. return redisTemplate.opsForList().size(key);
  432. }
  433. /**
  434. * 获取列表 指定范围内的所有值
  435. *
  436. * @param key
  437. * @param start
  438. * @param end
  439. * @return
  440. */
  441. public List<Object> listRange(String key, long start, long end) {
  442. return redisTemplate.opsForList().range(key, start, end);
  443. }
  444. /**
  445. * 删除 key 中 值为 value 的 count 个数.
  446. *
  447. * @param key
  448. * @param count
  449. * @param value
  450. * @return 成功删除的个数
  451. */
  452. public Long listRemove(String key, long count, Object value) {
  453. return redisTemplate.opsForList().remove(key, count, value);
  454. }
  455. /**
  456. * 删除 列表 [start,end] 以外的所有元素
  457. *
  458. * @param key
  459. * @param start
  460. * @param end
  461. */
  462. public void listTrim(String key, long start, long end) {
  463. redisTemplate.opsForList().trim(key, start, end);
  464. }
  465. /**
  466. * 将 key 右出栈,并左入栈到 key2
  467. *
  468. * @param key 右出栈的列表
  469. * @param key2 左入栈的列表
  470. * @return 操作的值
  471. */
  472. public Object rightPopAndLeftPush(String key, String key2) {
  473. return redisTemplate.opsForList().rightPopAndLeftPush(key, key2);
  474. }
  475. //set 操作 无序不重复集合
  476. /**
  477. * 添加 set 元素
  478. *
  479. * @param key
  480. * @param values
  481. * @return
  482. */
  483. public Long add(String key, String... values) {
  484. return redisTemplate.opsForSet().add(key, values);
  485. }
  486. //Zset 根据 socre 排序 不重复 每个元素附加一个 socre double类型的属性(double 可以重复)
  487. /**
  488. * 添加 ZSet 元素
  489. *
  490. * @param key
  491. * @param value
  492. * @param score
  493. */
  494. public boolean add(String key, Object value, double score) {
  495. return redisTemplate.opsForZSet().add(key, value, score);
  496. }
  497. /**
  498. * 获取两个集合的差集
  499. *
  500. * @param key
  501. * @param otherkey
  502. * @return
  503. */
  504. public Set<Object> difference(String key, String otherkey) {
  505. return redisTemplate.opsForSet().difference(key, otherkey);
  506. }
  507. /**
  508. * 获取 key 和 集合 collections 中的 key 集合的差集
  509. *
  510. * @param key
  511. * @param otherKeys
  512. * @return
  513. */
  514. public Set<Object> difference(String key, Collection<Object> otherKeys) {
  515. return redisTemplate.opsForSet().difference(key, otherKeys);
  516. }
  517. /**
  518. * 将 key 与 otherkey 的差集 ,添加到新的 newKey 集合中
  519. *
  520. * @param key
  521. * @param otherkey
  522. * @param newKey
  523. * @return 返回差集的数量
  524. */
  525. public Long differenceAndStore(String key, String otherkey, String newKey) {
  526. return redisTemplate.opsForSet().differenceAndStore(key, otherkey, newKey);
  527. }
  528. /**
  529. * 将 key 和 集合 collections 中的 key 集合的差集 添加到 newkey 集合中
  530. *
  531. * @param key
  532. * @param otherKeys
  533. * @param newKey
  534. * @return 返回差集的数量
  535. */
  536. public Long differenceAndStore(String key, Collection<Object> otherKeys, String newKey) {
  537. return redisTemplate.opsForSet().differenceAndStore(newKey, otherKeys, newKey);
  538. }
  539. /**
  540. * 删除一个或多个集合中的指定值
  541. *
  542. * @param key
  543. * @param values
  544. * @return 成功删除数量
  545. */
  546. public Long remove(String key, Object... values) {
  547. return redisTemplate.opsForSet().remove(key, values);
  548. }
  549. /**
  550. * 随机移除一个元素,并返回出来
  551. *
  552. * @param key
  553. * @return
  554. */
  555. public Object randomSetPop(String key) {
  556. return redisTemplate.opsForSet().pop(key);
  557. }
  558. /**
  559. * 随机获取一个元素
  560. *
  561. * @param key
  562. * @return
  563. */
  564. public Object randomSet(String key) {
  565. return redisTemplate.opsForSet().randomMember(key);
  566. }
  567. /**
  568. * 随机获取指定数量的元素,同一个元素可能会选中两次
  569. *
  570. * @param key
  571. * @param count
  572. * @return
  573. */
  574. public List<Object> randomSet(String key, long count) {
  575. return redisTemplate.opsForSet().randomMembers(key, count);
  576. }
  577. /**
  578. * 随机获取指定数量的元素,去重(同一个元素只能选择两一次)
  579. *
  580. * @param key
  581. * @param count
  582. * @return
  583. */
  584. public Set<Object> randomSetDistinct(String key, long count) {
  585. return redisTemplate.opsForSet().distinctRandomMembers(key, count);
  586. }
  587. /**
  588. * 将 key 中的 value 转入到 destKey 中
  589. *
  590. * @param key
  591. * @param value
  592. * @param destKey
  593. * @return 返回成功与否
  594. */
  595. public boolean moveSet(String key, Object value, String destKey) {
  596. return redisTemplate.opsForSet().move(key, value, destKey);
  597. }
  598. /**
  599. * 无序集合的大小
  600. *
  601. * @param key
  602. * @return
  603. */
  604. public Long setSize(String key) {
  605. return redisTemplate.opsForSet().size(key);
  606. }
  607. /**
  608. * 判断 set 集合中 是否有 value
  609. *
  610. * @param key
  611. * @param value
  612. * @return
  613. */
  614. public boolean isMember(String key, Object value) {
  615. return redisTemplate.opsForSet().isMember(key, value);
  616. }
  617. /**
  618. * 返回 key 和 othere 的并集
  619. *
  620. * @param key
  621. * @param otherKey
  622. * @return
  623. */
  624. public Set<Object> unionSet(String key, String otherKey) {
  625. return redisTemplate.opsForSet().union(key, otherKey);
  626. }
  627. /**
  628. * 返回 key 和 otherKeys 的并集
  629. *
  630. * @param key
  631. * @param otherKeys key 的集合
  632. * @return
  633. */
  634. public Set<Object> unionSet(String key, Collection<Object> otherKeys) {
  635. return redisTemplate.opsForSet().union(key, otherKeys);
  636. }
  637. /**
  638. * 将 key 与 otherKey 的并集,保存到 destKey 中
  639. *
  640. * @param key
  641. * @param otherKey
  642. * @param destKey
  643. * @return destKey 数量
  644. */
  645. public Long unionAndStoreSet(String key, String otherKey, String destKey) {
  646. return redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey);
  647. }
  648. /**
  649. * 将 key 与 otherKey 的并集,保存到 destKey 中
  650. *
  651. * @param key
  652. * @param otherKeys
  653. * @param destKey
  654. * @return destKey 数量
  655. */
  656. public Long unionAndStoreSet(String key, Collection<Object> otherKeys, String destKey) {
  657. return redisTemplate.opsForSet().unionAndStore(key, otherKeys, destKey);
  658. }
  659. /**
  660. * 返回集合中所有元素
  661. *
  662. * @param key
  663. * @return
  664. */
  665. public Set<Object> members(String key) {
  666. return redisTemplate.opsForSet().members(key);
  667. }
  668. /**
  669. * 批量添加 Zset Set<TypedTuple<Object>> tuples = new HashSet<>(); TypedTuple<Object>
  670. * objectTypedTuple1 = new DefaultTypedTuple<Object>("zset-5",9.6);
  671. * tuples.add(objectTypedTuple1);
  672. *
  673. * @param key
  674. * @param tuples
  675. * @return
  676. */
  677. public Long batchAddZset(String key, Set<TypedTuple<Object>> tuples) {
  678. return redisTemplate.opsForZSet().add(key, tuples);
  679. }
  680. /**
  681. * Zset 删除一个或多个元素
  682. *
  683. * @param key
  684. * @param values
  685. * @return
  686. */
  687. public Long removeZset(String key, String... values) {
  688. return redisTemplate.opsForZSet().remove(key, values);
  689. }
  690. /**
  691. * 对指定的 zset 的 value 值 , socre 属性做增减操作
  692. *
  693. * @param key
  694. * @param value
  695. * @param score
  696. * @return
  697. */
  698. public Double incrementScore(String key, Object value, double score) {
  699. return redisTemplate.opsForZSet().incrementScore(key, value, score);
  700. }
  701. /**
  702. * 获取 key 中指定 value 的排名(从0开始,从小到大排序)
  703. *
  704. * @param key
  705. * @param value
  706. * @return
  707. */
  708. public Long rank(String key, Object value) {
  709. return redisTemplate.opsForZSet().rank(key, value);
  710. }
  711. /**
  712. * 获取 key 中指定 value 的排名(从0开始,从大到小排序)
  713. *
  714. * @param key
  715. * @param value
  716. * @return
  717. */
  718. public Long reverseRank(String key, Object value) {
  719. return redisTemplate.opsForZSet().reverseRank(key, value);
  720. }
  721. /**
  722. * 获取索引区间内的排序结果集合(从0开始,从小到大,带上分数)
  723. *
  724. * @param key
  725. * @param start
  726. * @param end
  727. * @return
  728. */
  729. public Set<TypedTuple<Object>> rangeWithScores(String key, long start, long end) {
  730. return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
  731. }
  732. /**
  733. * 获取索引区间内的排序结果集合(从0开始,从小到大,只有列名)
  734. *
  735. * @param key
  736. * @param start
  737. * @param end
  738. * @return
  739. */
  740. public Set<Object> range(String key, long start, long end) {
  741. return redisTemplate.opsForZSet().range(key, start, end);
  742. }
  743. /**
  744. * 获取分数范围内的 [min,max] 的排序结果集合 (从小到大,只有列名)
  745. *
  746. * @param key
  747. * @param min
  748. * @param max
  749. * @return
  750. */
  751. public Set<Object> rangeByScore(String key, double min, double max) {
  752. return redisTemplate.opsForZSet().rangeByScore(key, min, max);
  753. }
  754. /**
  755. * 返回 分数范围内 指定 count 数量的元素集合, 并且从 offset 下标开始(从小到大,不带分数的集合)
  756. *
  757. * @param key
  758. * @param min
  759. * @param max
  760. * @param offset 从指定下标开始
  761. * @param count 输出指定元素数量
  762. * @return
  763. */
  764. public Set<Object> rangeByScore(String key, double min, double max, long offset, long count) {
  765. return redisTemplate.opsForZSet().rangeByScore(key, min, max, offset, count);
  766. }
  767. /**
  768. * 返回 分数范围内 指定 count 数量的元素集合, 并且从 offset 下标开始(从小到大,带分数的集合)
  769. *
  770. * @param key
  771. * @param min
  772. * @param max
  773. * @param offset 从指定下标开始
  774. * @param count 输出指定元素数量
  775. * @return
  776. */
  777. public Set<TypedTuple<Object>> rangeByScoreWithScores(String key, double min, double max,
  778. long offset, long count) {
  779. return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max, offset, count);
  780. }
  781. /**
  782. * 获取分数范围内的 [min,max] 的排序结果集合 (从小到大,集合带分数)
  783. *
  784. * @param key
  785. * @param min
  786. * @param max
  787. * @return
  788. */
  789. public Set<TypedTuple<Object>> rangeByScoreWithScores(String key, double min, double max) {
  790. return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
  791. }
  792. /**
  793. * 获取索引区间内的排序结果集合(从0开始,从大到小,只有列名)
  794. *
  795. * @param key
  796. * @param start
  797. * @param end
  798. * @return
  799. */
  800. public Set<Object> reverseRange(String key, long start, long end) {
  801. return redisTemplate.opsForZSet().reverseRange(key, start, end);
  802. }
  803. /**
  804. * 获取索引区间内的排序结果集合(从0开始,从大到小,带上分数)
  805. *
  806. * @param key
  807. * @param start
  808. * @param end
  809. * @return
  810. */
  811. public Set<TypedTuple<Object>> reverseRangeWithScores(String key, long start, long end) {
  812. return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end);
  813. }
  814. /**
  815. * 获取分数范围内的 [min,max] 的排序结果集合 (从大到小,集合不带分数)
  816. *
  817. * @param key
  818. * @param min
  819. * @param max
  820. * @return
  821. */
  822. public Set<Object> reverseRangeByScore(String key, double min, double max) {
  823. return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
  824. }
  825. /**
  826. * 获取分数范围内的 [min,max] 的排序结果集合 (从大到小,集合带分数)
  827. *
  828. * @param key
  829. * @param min
  830. * @param max
  831. * @return
  832. */
  833. public Set<TypedTuple<Object>> reverseRangeByScoreWithScores(String key, double min,
  834. double max) {
  835. return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, min, max);
  836. }
  837. /**
  838. * 返回 分数范围内 指定 count 数量的元素集合, 并且从 offset 下标开始(从大到小,带分数的集合)
  839. *
  840. * @param key
  841. * @param min
  842. * @param max
  843. * @param offset 从指定下标开始
  844. * @param count 输出指定元素数量
  845. * @return
  846. */
  847. public Set<TypedTuple<Object>> reverseRangeByScoreWithScores(String key, double min, double max,
  848. long offset, long count) {
  849. return redisTemplate.opsForZSet()
  850. .reverseRangeByScoreWithScores(key, min, max, offset, count);
  851. }
  852. /**
  853. * 返回 分数范围内 指定 count 数量的元素集合, 并且从 offset 下标开始(从大到小,不带分数的集合)
  854. *
  855. * @param key
  856. * @param min
  857. * @param max
  858. * @param offset 从指定下标开始
  859. * @param count 输出指定元素数量
  860. * @return
  861. */
  862. public Set<Object> reverseRangeByScore(String key, double min, double max, long offset,
  863. long count) {
  864. return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, offset, count);
  865. }
  866. /**
  867. * 返回指定分数区间 [min,max] 的元素个数
  868. *
  869. * @param key
  870. * @param min
  871. * @param max
  872. * @return
  873. */
  874. public long countZSet(String key, double min, double max) {
  875. return redisTemplate.opsForZSet().count(key, min, max);
  876. }
  877. /**
  878. * 返回 zset 集合数量
  879. *
  880. * @param key
  881. * @return
  882. */
  883. public long sizeZset(String key) {
  884. return redisTemplate.opsForZSet().size(key);
  885. }
  886. /**
  887. * 获取指定成员的 score 值
  888. *
  889. * @param key
  890. * @param value
  891. * @return
  892. */
  893. public Double score(String key, Object value) {
  894. return redisTemplate.opsForZSet().score(key, value);
  895. }
  896. /**
  897. * 删除指定索引位置的成员,其中成员分数按( 从小到大 )
  898. *
  899. * @param key
  900. * @param start
  901. * @param end
  902. * @return
  903. */
  904. public Long removeRange(String key, long start, long end) {
  905. return redisTemplate.opsForZSet().removeRange(key, start, end);
  906. }
  907. /**
  908. * 删除指定 分数范围 内的成员 [main,max],其中成员分数按( 从小到大 )
  909. *
  910. * @param key
  911. * @param min
  912. * @param max
  913. * @return
  914. */
  915. public Long removeRangeByScore(String key, double min, double max) {
  916. return redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
  917. }
  918. /**
  919. * key 和 other 两个集合的并集,保存在 destKey 集合中, 列名相同的 score 相加
  920. *
  921. * @param key
  922. * @param otherKey
  923. * @param destKey
  924. * @return
  925. */
  926. public Long unionAndStoreZset(String key, String otherKey, String destKey) {
  927. return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
  928. }
  929. /**
  930. * key 和 otherKeys 多个集合的并集,保存在 destKey 集合中, 列名相同的 score 相加
  931. *
  932. * @param key
  933. * @param otherKeys
  934. * @param destKey
  935. * @return
  936. */
  937. public Long unionAndStoreZset(String key, Collection<String> otherKeys, String destKey) {
  938. return redisTemplate.opsForZSet().unionAndStore(key, otherKeys, destKey);
  939. }
  940. /**
  941. * key 和 otherKey 两个集合的交集,保存在 destKey 集合中
  942. *
  943. * @param key
  944. * @param otherKey
  945. * @param destKey
  946. * @return
  947. */
  948. public Long intersectAndStore(String key, String otherKey, String destKey) {
  949. return redisTemplate.opsForZSet().intersectAndStore(key, otherKey, destKey);
  950. }
  951. /**
  952. * key 和 otherKeys 多个集合的交集,保存在 destKey 集合中
  953. *
  954. * @param key
  955. * @param otherKeys
  956. * @param destKey
  957. * @return
  958. */
  959. public Long intersectAndStore(String key, Collection<String> otherKeys, String destKey) {
  960. return redisTemplate.opsForZSet().intersectAndStore(key, otherKeys, destKey);
  961. }
  962. /**
  963. * 获取分布式锁
  964. *
  965. * @param lockKey
  966. * @param value setLock时,若锁已存在,则判断传入value与锁中value是否一致,一致则返回成功。
  967. * @param expireSeconds: 秒
  968. * @return
  969. */
  970. public boolean setLock(String lockKey, String value, int expireSeconds) {
  971. boolean flag = false;
  972. String script = "if redis.call('setNx',KEYS[1],ARGV[1]) then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";
  973. RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
  974. Object result = redisTemplate
  975. .execute(redisScript, Collections.singletonList(lockKey), value, expireSeconds);
  976. if (SUCCESS.equals(result)) {
  977. flag = true;
  978. }
  979. return flag;
  980. }
  981. /**
  982. * 释放分布式锁
  983. *
  984. * @param lockKey
  985. * @param value
  986. * @return
  987. */
  988. public boolean releaseLock(String lockKey, String value) {
  989. String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
  990. RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
  991. Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),
  992. value);
  993. return SUCCESS.equals(result);
  994. }
  995. }

TRbtTestController

  1. package com.test.invoice.contorller;
  2. import com.sun.xml.internal.fastinfoset.algorithm.BooleanEncodingAlgorithm;
  3. import com.test.invoice.data.TRbtTestData;
  4. import com.test.invoice.data.TRbtTestDataParam;
  5. import com.test.invoice.enums.ResponseCode;
  6. import com.test.invoice.model.TRbtUserEntity;
  7. import com.test.invoice.service.producer.ITRbtTestService;
  8. import com.test.invoice.util.RedisUtil;
  9. import com.test.invoice.vo.LoginRequestVO;
  10. import com.test.invoice.vo.ResponseVO;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.web.bind.annotation.PostMapping;
  13. import org.springframework.web.bind.annotation.RequestBody;
  14. import org.springframework.web.bind.annotation.RequestMapping;
  15. import org.springframework.web.bind.annotation.RestController;
  16. import io.swagger.annotations.Api;
  17. import io.swagger.annotations.ApiOperation;
  18. import org.springframework.web.bind.annotation.*;
  19. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  20. import javax.annotation.Resource;
  21. /**
  22. *
  23. * 生产者:业务微服务-测试框架系统控制类
  24. *
  25. * @author:
  26. * @version:
  27. * @date: 2019-08-12 09:53
  28. */
  29. @RestController
  30. @Api(description = "测试框架系统控制类")
  31. public class TRbtTestController {
  32. @Autowired
  33. private RedisUtil redisUtil;
  34. @PostMapping("/Test/RedisTest")
  35. @ApiOperation(value="系统框架测试-RedisTest",httpMethod = "POST",response = ResponseVO.class,notes = "系统框架测试-RedisTest")
  36. public ResponseVO<String> RedisTest(){
  37. ResponseVO<String> responseVO = new ResponseVO<>();
  38. //设置 Redis
  39. redisUtil.set("luomaKey","luomaValue");
  40. //获取 Redis
  41. String value = redisUtil.get("luomaKey");
  42. responseVO.setCode(ResponseCode.OK.value());
  43. responseVO.setMsg(ResponseCode.OK.getDescription());
  44. responseVO.setData(value);
  45. return responseVO;
  46. }
  47. }

使用 Postman 测试

直接访问

http://localhost:18800/Test/RedisTest

结果

  1. {
  2. "code": 2000,
  3. "msg": "Success",
  4. "data": "luomaValue"
  5. }

使用 RedisDesktopManager 查看 Redis 值