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 j = new Jackson2JsonRedisSerializer(Object.class);
        // value       fastJsonRedisSerializer
        template.setValueSerializer(j);
        template.setHashValueSerializer(j);
        // key      StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    public JedisPool redisPoolFactory()  throws Exception {
        log.info("redis  :" + host + ":" + port);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //     pool jmx    ,   true
        jedisPoolConfig.setJmxEnabled(true);
        int redisTimeout = (int)timeout.getSeconds();
        //       500
        jedisPoolConfig.setMaxTotal(jedisMaxActive);
        //        50
        jedisPoolConfig.setMaxIdle(jedisMaxIdle);
        //      30s
        jedisPoolConfig.setMaxWaitMillis(jedisMaxWait.getSeconds() * 1000);
        /*//   Jedis   ,          
        jedisPoolConfig.setTestOnBorrow(true);
        //         ,          
        jedisPoolConfig.setTestOnReturn(true);
        //                   
        jedisPoolConfig.setTestWhileIdle(true);*/
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, redisTimeout, password);
        return jedisPool;
    }

}

좋은 웹페이지 즐겨찾기