java实现redis锁

添加依赖


   redis.clients
   jedis
   2.9.0


   org.springframework.boot
   spring-boot-starter-data-redis

配置

spring:
  redis:
    host: 127.0.0.1
    port: 6379
代码
@Service
@Slf4j
public class RedisLockService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public boolean lock(String key, String value, int expire) {
        return set(key, value, "NX", "EX", expire);

    }

  
    public void unlock(String key, String value) {
        try {
            String currentValue = redisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
                //解锁就是删掉key的操作
                redisTemplate.opsForValue().getOperations().delete(key);
            }
        } catch (Exception e) {
            log.error("【redis分布式锁】解锁异常,{} ", e);
        }
    }

    public boolean set(final String key, final String value, final String nxxx, final String expx, final long time)       {
        Object result = redisTemplate.execute(new RedisCallback() {

            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer serializer = redisTemplate.getStringSerializer();
                redisConnection.execute("set", new byte[][]{
                        serializer.serialize(key), serializer.serialize(value),
                        serializer.serialize(nxxx), serializer.serialize(expx),
                        SafeEncoder.encode(String.valueOf(time))

                });
                return true;
            }
        });
        return false;
    }
} 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(java)