码迷,mamicode.com
首页 > 其他好文 > 详细

redis锁

时间:2020-02-13 17:00:07      阅读:18      评论:0      收藏:0      [点我收藏+]

标签:dom   void   connect   key   ota   des   string   not   redist   

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锁

标签:dom   void   connect   key   ota   des   string   not   redist   

原文地址:https://www.cnblogs.com/lostguangtou/p/12303866.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!