package com.ivhs.crm.utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCommands;
import java.util.UUID;
/**
* @Description: redis锁
* @Version: 1.0
*/
@Component
public class RedisLock {
@Autowired
private RedisTemplate redisTemplate;
public boolean setLock(String key,long expire){
String result = (String) redisTemplate.execute(new RedisCallbackLock(key,expire));
return !StringUtils.isEmpty(result);
}
public void unLock(String key){
redisTemplate.delete(key);
}
class RedisCallbackLock implements RedisCallback{
private String key;
private long expire;//单位秒
public RedisCallbackLock(String key, long expire) {
this.key = key;
this.expire = expire;
}
/**
* @Description 如果key存在返回null否则返回OK
* commands参数:如果取NX,则只有当key不存在是才进行set,如果取XX,则只有当key已经存在时才进行set
* EX代表秒,PX代表毫秒
*/
@Override
public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
JedisCommands commands = (JedisCommands) redisConnection.getNativeConnection();
String uuid = UUID.randomUUID().toString();
return commands.set(key, uuid, "NX", "EX", expire);
}
}
}