redis锁
Posted lostguangtou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redis锁相关的知识,希望对你有一定的参考价值。
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);
}
}
}
以上是关于redis锁的主要内容,如果未能解决你的问题,请参考以下文章