|  |  |  | 
|---|
|  |  |  | package com.zy.common.utils; | 
|---|
|  |  |  |  | 
|---|
|  |  |  | import com.baomidou.mybatisplus.toolkit.StringUtils; | 
|---|
|  |  |  | import org.springframework.beans.factory.annotation.Autowired; | 
|---|
|  |  |  | import org.springframework.data.redis.core.RedisTemplate; | 
|---|
|  |  |  | import org.springframework.data.redis.core.StringRedisTemplate; | 
|---|
|  |  |  | 
|---|
|  |  |  | @Autowired | 
|---|
|  |  |  | private RedisTemplate redisTemplate; | 
|---|
|  |  |  |  | 
|---|
|  |  |  | @Autowired | 
|---|
|  |  |  | private StringRedisTemplate stringRedisTemplate; | 
|---|
|  |  |  |  | 
|---|
|  |  |  | private static final String LOCK_PREFIX = "lock:"; | 
|---|
|  |  |  | private static final long DEFAULT_EXPIRE_TIME = 10; // 默认锁过期时间,单位为分钟 | 
|---|
|  |  |  |  | 
|---|
|  |  |  | public RedisUtil(RedisTemplate redisTemplate) { | 
|---|
|  |  |  | this.redisTemplate = redisTemplate; | 
|---|
|  |  |  | } | 
|---|
|  |  |  |  | 
|---|
|  |  |  | /** | 
|---|
|  |  |  | * Redis加锁的操作 | 
|---|
|  |  |  | */ | 
|---|
|  |  |  | public Boolean tryLock(String key) { | 
|---|
|  |  |  | String redisKey = LOCK_PREFIX + key; | 
|---|
|  |  |  | return redisTemplate.opsForValue().setIfAbsent(redisKey, "locked", DEFAULT_EXPIRE_TIME, TimeUnit.MINUTES); | 
|---|
|  |  |  | } | 
|---|
|  |  |  |  | 
|---|
|  |  |  | /** | 
|---|
|  |  |  | * Redis解锁的操作 | 
|---|
|  |  |  | */ | 
|---|
|  |  |  | public void unlock(String lockKey) { | 
|---|
|  |  |  | String redisKey = LOCK_PREFIX + lockKey; | 
|---|
|  |  |  | redisTemplate.delete(redisKey); | 
|---|
|  |  |  | } | 
|---|
|  |  |  |  | 
|---|
|  |  |  | /** | 
|---|
|  |  |  | 
|---|
|  |  |  | public boolean set(String key, Object value) { | 
|---|
|  |  |  | try { | 
|---|
|  |  |  | redisTemplate.opsForValue().set(key, value); | 
|---|
|  |  |  | long start = System.currentTimeMillis(); | 
|---|
|  |  |  | while (System.currentTimeMillis() - start < 10000) {//有效期10s | 
|---|
|  |  |  | Object o = redisTemplate.opsForValue().get(key); | 
|---|
|  |  |  | if (o == null) { | 
|---|
|  |  |  | continue; | 
|---|
|  |  |  | } | 
|---|
|  |  |  |  | 
|---|
|  |  |  | if (o.equals(value)) { | 
|---|
|  |  |  | break; | 
|---|
|  |  |  | } | 
|---|
|  |  |  | } | 
|---|
|  |  |  | return true; | 
|---|
|  |  |  | } catch (Exception e) { | 
|---|
|  |  |  | e.printStackTrace(); | 
|---|