| | |
| | | package com.terra.common.service; |
| | | |
| | | import com.terra.common.entity.all.RedisCacheKey; |
| | | import com.terra.common.entity.all.SettingData; |
| | | import lombok.Getter; |
| | | import org.springframework.data.redis.core.RedisTemplate; |
| | | import org.springframework.stereotype.Service; |
| | | |
| | | import javax.annotation.Resource; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | import java.util.UUID; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * Redis服务类 |
| | | * @author WWW |
| | | */ |
| | | @Getter |
| | | @Service |
| | | public class RedisService { |
| | | @Resource |
| | | private RedisTemplate<String, Object> redisTemplate; |
| | | |
| | | /** |
| | | * -- GETTER -- |
| | | * 获取Redis模板 |
| | | */ |
| | | public RedisTemplate<String, Object> getRedisTemplate() { |
| | | return redisTemplate; |
| | | } |
| | | @Resource |
| | | private RedisTemplate<String, Object> redisTemplate; |
| | | |
| | | /** |
| | | * 设置值到redis中 |
| | |
| | | /** |
| | | * 清空指定键前缀 |
| | | * |
| | | * @param subKeyString 键前缀 |
| | | * @param prefix 键前缀 |
| | | */ |
| | | public void clearKeys(String subKeyString) { |
| | | Set<String> keys = redisTemplate.keys(subKeyString + "*"); |
| | | public void clearKeys(String prefix) { |
| | | Set<String> keys = redisTemplate.keys(prefix + "*"); |
| | | if (!keys.isEmpty()) { |
| | | redisTemplate.delete(keys); |
| | | } |
| | |
| | | put(key, list, minutes, TimeUnit.MINUTES); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 获取分布式锁 |
| | | */ |
| | | public boolean tryLock(String key, long expireTime, TimeUnit timeUnit) { |
| | | String lockKey = RedisCacheKey.resourceLockKey(key); |
| | | String value = UUID.randomUUID().toString(); |
| | | |
| | | return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(lockKey, value, expireTime, timeUnit)); |
| | | } |
| | | |
| | | /** |
| | | * 释放锁 |
| | | */ |
| | | public void releaseLock(String key) { |
| | | String lockKey = RedisCacheKey.resourceLockKey(key); |
| | | |
| | | redisTemplate.delete(lockKey); |
| | | } |
| | | } |