之前用redisson来实现redis分布式锁(参考https://blog.csdn.net/lfwer/article/details/83901402),搭建起来比较麻烦,而且会有重复配置,偶尔看到一篇基于redisTemplate的redis的分布式锁的实现方式,试了试确实好用,因此转载过来。
原文地址:https://blog.csdn.net/qq_28397259/article/details/80839072?utm_source=blogkpcl13
package com.chinaway.snow.config.redis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author superchen
* @since 2018/5/16
**/
@Component
@Slf4j
public class RedisDistributedLock {
@Resource
private StringRedisTemplate stringRedisTemplate;
public static final String UNLOCK_LUA;
static {
StringBuilder sb = new StringBuilder();
sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] ");
sb.append("then ");
sb.append(" return redis.call(\"del\",KEYS[1]) ");
sb.append("else ");
sb.append(" return 0 ");
sb.append("end ");
UNLOCK_LUA = sb.toString();
}
public boolean setLock(String key, long expire) {
try {
RedisCallback callback = (connection) -> {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
String uuid = UUID.randomUUID().toString();
return commands.set(key, uuid, "NX", "PX", expire);
};
String result = stringRedisTemplate.execute(callback);
return !StringUtils.isEmpty(result);
} catch (Exception e) {
log.error("set redis occured an exception", e);
}
return false;
}
public String get(String key) {
try {
RedisCallback callback = (connection) -> {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
return commands.get(key);
};
String result = stringRedisTemplate.execute(callback);
return result;
} catch (Exception e) {
log.error("get redis occured an exception", e);
}
return "";
}
public boolean releaseLock(String key, String requestId) {
// 释放锁的时候,有可能因为持锁之后方法执行时间大于锁的有效期,此时有可能已经被另外一个线程持有锁,所以不能直接删除
try {
List keys = new ArrayList<>();
keys.add(key);
List args = new ArrayList<>();
args.add(requestId);
// 使用lua脚本删除redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁
// spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本的异常,所以只能拿到原redis的connection来执行脚本
RedisCallback callback = (connection) -> {
Object nativeConnection = connection.getNativeConnection();
// 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行
// 集群模式
if (nativeConnection instanceof JedisCluster) {
return (Long) ((JedisCluster) nativeConnection).eval(UNLOCK_LUA, keys, args);
}
// 单机模式
else if (nativeConnection instanceof Jedis) {
return (Long) ((Jedis) nativeConnection).eval(UNLOCK_LUA, keys, args);
}
return 0L;
};
Long result = stringRedisTemplate.execute(callback);
return result != null && result > 0;
} catch (Exception e) {
log.error("release lock occured an exception", e);
} finally {
// 清除掉ThreadLocal中的数据,避免内存溢出
//lockFlag.remove();
}
return false;
}
}
org.springframework.boot
spring-boot-starter-redis
# Redis数据库索引(默认为0)
spring.redis.database=6
# Redis服务器地址
spring.redis.host=172.16.1.9
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=500
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=5000
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
import com.chinaway.snow.constant.RedisConstant;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.util.HashMap;
import java.util.Map;
/**
* Description: TODO
*
* @author Asdpboy Yan 2018年3月1日 上午11:06:34
* @ClassName: RedisCacheConfig
* @see
*/
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
//自定义缓存key生成策略
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
StringBuffer sb = new StringBuffer();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append("_" + obj.toString());
}
return sb.toString();
}
};
}
//缓存管理器
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
//设置默认缓存过期时间
cacheManager.setDefaultExpiration(10000);
Map expiresMap = new HashMap<>();
//用户当前行程设置1小时过期
expiresMap.put(RedisConstant.currentTravelsByDriverId, 3600L);
//根据id获取行程详情设置1小时过期
expiresMap.put(RedisConstant.detailTravelsById, 3600L);
cacheManager.setExpires(expiresMap);
return cacheManager;
}
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template);//设置序列化工具
template.afterPropertiesSet();
return template;
}
private void setSerializer(StringRedisTemplate template) {
@SuppressWarnings({"rawtypes", "unchecked"})
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.chinaway.snow.config.redis.RedisDistributedLock;
import com.chinaway.snow.dao.bill.BillTravelSalaryMapper;
import javax.annotation.PreDestroy;
import java.util.UUID;
/**
* @Description:
* @ClassName: DriverSalaryJob
* @Author: Liu FangWei
* @Date: 2018/12/23 14:18
* @Version: 1.0
*/
@Component
@Slf4j
public class Test {
@Autowired
private RedisDistributedLock redisDistributedLock;
private String requestId;
private static final String key = "testKey";
@Scheduled(cron = "0 */1 * * * ?")
public void execute() {
//获得锁
boolean lockOk = redisDistributedLock.setLock(key, 3600000);
try {
if (lockOk) {
Long start = System.currentTimeMillis();
//记录当前锁对应的requestId
requestId = redisDistributedLock.get(key);
log.info("star test.");
//业务代码,省略...
log.info("end test,耗时:{}s", count, (System.currentTimeMillis() - start) / 1000);
}
} catch (Exception ex) {
log.error("test error", ex);
} finally {
if (requestId != null)
redisDistributedLock.releaseLock(key, requestId);
}
}
//应用注销时需要删除key
@PreDestroy
public void destroy() {
if (requestId != null)
redisDistributedLock.releaseLock(key, requestId);
}
}
就是这么简单,赶快来试试吧。