| | |
| | | import org.springframework.data.redis.core.RedisCallback; |
| | | import org.springframework.data.redis.core.RedisTemplate; |
| | | import org.springframework.data.redis.core.StringRedisTemplate; |
| | | import org.springframework.data.redis.core.script.DefaultRedisScript; |
| | | import org.springframework.stereotype.Component; |
| | | import org.springframework.util.CollectionUtils; |
| | | |
| | | import java.util.Collections; |
| | | import java.util.HashMap; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | |
| | | } |
| | | redisTemplate.execute((RedisCallback<Void>) connection -> null); |
| | | return true; |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | public boolean trySetStringIfAbsent(String key, String value, long timeSeconds) { |
| | | if (key == null || value == null) { |
| | | return false; |
| | | } |
| | | try { |
| | | Boolean result; |
| | | if (timeSeconds > 0) { |
| | | result = stringRedisTemplate.opsForValue().setIfAbsent(key, value, timeSeconds, TimeUnit.SECONDS); |
| | | } else { |
| | | result = stringRedisTemplate.opsForValue().setIfAbsent(key, value); |
| | | } |
| | | return Boolean.TRUE.equals(result); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | public boolean compareAndDelete(String key, String expectedValue) { |
| | | if (key == null || expectedValue == null) { |
| | | return false; |
| | | } |
| | | try { |
| | | DefaultRedisScript<Long> script = new DefaultRedisScript<>(); |
| | | script.setScriptText( |
| | | "if redis.call('get', KEYS[1]) == ARGV[1] then " + |
| | | "return redis.call('del', KEYS[1]) " + |
| | | "else return 0 end" |
| | | ); |
| | | script.setResultType(Long.class); |
| | | Long result = stringRedisTemplate.execute(script, Collections.singletonList(key), expectedValue); |
| | | return result != null && result > 0; |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | return false; |
| | |
| | | |
| | | |
| | | } |
| | | |