package com.supersavedriving.user.modular.system.util; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * Redis工具类 */ @Component public class RedisUtil { @Resource private RedisTemplate redisTemplate; /** * 向redis中存储字符串没有过期时间 * @param key * @param value */ public void setStrValue(String key, String value){ redisTemplate.opsForValue().set(key, value); } /** * 以分钟为单位设置存储值(设置过期时间) * @param key * @param value * @param time 秒 */ public void setStrValue(String key, String value, int time){ redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } /** * 从redis中获取值 * @param key * @return */ public String getValue(String key){ return (String) redisTemplate.opsForValue().get(key); } /** * 删除key * @param key */ public void remove(String key){ redisTemplate.delete(key); } /** * 删除Set集合中的值 * @param key * @param members */ public void delSetValue(String key, String...members){ redisTemplate.opsForSet().remove(key, members); } /** * redis加锁 * @param key * @param value * @param time * @return */ public boolean lock(String key, String value, int time){ key += "_lock"; return redisTemplate.opsForValue().setIfAbsent(key, value); } /** * 获取redis锁 * @return */ public boolean lock(){ try { boolean b = lock(5); if(!b){ int num1 = 1; while (num1 <= 10){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } b = lock(5); if(b){ return true; }else{ num1++; } } return false; } return b; }catch (Exception e){ e.printStackTrace(); }finally { unlock(); } return false; } public boolean lock(String key){ try { boolean b = lock(key,5); if(!b){ int num1 = 1; while (num1 <= 10){ try { Thread.sleep(1000);//等待1秒 } catch (InterruptedException e) { e.printStackTrace(); } b = lock(5); if(b){ return true; }else{ num1++; } } return false; } return b; }catch (Exception e){ e.printStackTrace(); unlock(); } return false; } /** * 获取redis锁 * @param time * @return */ public boolean lock(String key, int time){ String uuid = UUID.randomUUID().toString(); return lock(key, uuid, time); } /** * 获取redis锁 * @param time * @return */ public boolean lock(int time){ String uuid = UUID.randomUUID().toString(); return lock("redis", uuid, time); } /** * redis释放锁 * @param key * @return */ public boolean unlock(String key){ return redisTemplate.delete(key); } /** * 删除锁 * @return */ public boolean unlock(){ return unlock("redis"); } }