redis 자물쇠 추가
5942 단어 자바
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.UUID;
public class JedisService {
@Autowired
private JedisPool jedisPool;
/**
*
* @param lockKey key
* @param second ( )
* @param t
* @return
* @throws Exception
*/
public String redisLock(String lockKey,int second, T t)throws Exception{
String requestId = UUID.randomUUID().toString();
//
int expireTime = second*1000;
boolean isRun = true;
while (isRun) {
try (Jedis jedis = jedisPool.getResource()){
//
boolean getLock = RedisLockTool.tryGetDistributedLock(jedis, lockKey, requestId, expireTime);
if (getLock) {
//TODO ( , )
//
RedisLockTool.releaseDistributedLock(jedis, lockKey, requestId);
isRun = false;
}
} catch (Exception e) {
isRun = false;
return " , :"+e.getMessage();
} finally {
Thread.sleep(50);
}
}
return "SUCCESS";
}
} RedisLockTool 클래스 코드:
import redis.clients.jedis.Jedis;
import java.util.Collections;
public class RedisLockTool {
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "nx";
private static final String SET_WITH_EXPIRE_TIME = "px";
private static final Long RELEASE_SUCCESS = 1L;
/**
*
* @param jedis Redis
* @param lockKey
* @param requestId
* @param expireTime
* @return
*/
public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
return false;
}
/**
*
* @param jedis Redis
* @param lockKey
* @param requestId
* @return
*/
public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
} redis 관련 설정:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.time.Duration;
@Configuration
@Slf4j
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private Duration timeout;
@Value("${spring.redis.jedis.pool.max-active:500}")
private int jedisMaxActive;
@Value("${spring.redis.jedis.pool.max-idle:50}")
private int jedisMaxIdle;
@Value("${spring.redis.jedis.pool.max-wait:30s}")
private Duration jedisMaxWait;
@Bean("userRedisTemplate")
public RedisTemplate redisTemplate(
RedisConnectionFactory redisConnectionFactory) {
RedisTemplate template = new RedisTemplate<>();
// fastjson
Jackson2JsonRedisSerializer 이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.