¶Ô±ÈÐÂÎļþ |
| | |
| | | package com.aps.common.redis.service; |
| | | |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.data.redis.core.RedisTemplate; |
| | | import org.springframework.data.redis.core.script.DefaultRedisScript; |
| | | import org.springframework.data.redis.core.script.RedisScript; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import java.time.Duration; |
| | | import java.util.Collections; |
| | | |
| | | /** |
| | | * Redis åå¸å¼é |
| | | * |
| | | **/ |
| | | @Component |
| | | public class RedisLockUtils { |
| | | |
| | | @Autowired |
| | | private RedisTemplate redisTemplate; |
| | | |
| | | //åå¸å¼éè¿ææ¶é´ s å¯ä»¥æ ¹æ®ä¸å¡èªå·±è°è |
| | | private static final Long LOCK_REDIS_TIMEOUT = 10L; |
| | | //åå¸å¼éä¼ç è³ åæ¬¡å°è¯è·å ççå¾
æ¶é´ ms å¯ä»¥æ ¹æ®ä¸å¡èªå·±è°è |
| | | public static final Long LOCK_REDIS_WAIT = 500L; |
| | | |
| | | |
| | | /** |
| | | * å é |
| | | **/ |
| | | public Boolean getLock(String key,String value,Long timeoutSeconds){ |
| | | Boolean lockStatus = this.redisTemplate.opsForValue().setIfAbsent(key,value, Duration.ofSeconds(timeoutSeconds)); |
| | | return lockStatus; |
| | | } |
| | | |
| | | /** |
| | | * éæ¾é |
| | | **/ |
| | | public Long releaseLock(String key,String value){ |
| | | String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; |
| | | RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript,Long.class); |
| | | Long releaseStatus = (Long)this.redisTemplate.execute(redisScript, Collections.singletonList(key),value); |
| | | return releaseStatus; |
| | | } |
| | | } |