现在的位置: 首页 > 编程语言 > 正文

springbootredis分布式锁代码实例

2020年02月13日 编程语言 ⁄ 共 1543字 ⁄ 字号 评论关闭

这篇文章主要介绍了springboot redis分布式锁代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

随着微服务等分布式架构的快速发展及应用,在很多情况下,我们都会遇到在并发情况下多个线程竞争资源的情况,比如我们耳熟能详的秒杀活动,多平台多用户对同一个资源进行操作等场景等。分布式锁的实现方式有很多种,比如基于数据库、Zookeeper、Redis等,本文我们主要介绍Spring Boot整合Redis实现分布式锁。

工具类如下:

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisCallback;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.stereotype.Component;import redis.clients.jedis.Protocol;import redis.clients.util.SafeEncoder;import java.io.Serializable;@Componentpublic class RedisUtils { @Autowired private RedisTemplate redisTemplate; public RedisTemplate getRedisTemplate() { return this.redisTemplate; } /** * 设置redis分布式锁 * @param key * @param value * @param expire 锁过期时间 * @return */ public boolean tryLock(final String key, final Serializable value, final long expire){ boolean isSuccess = (boolean) redisTemplate.execute((RedisCallback) connection -> { RedisSerializer valueSerializer = redisTemplate.getValueSerializer(); RedisSerializer keySerializer = redisTemplate.getKeySerializer(); Object object = connection.execute("set",keySerializer.serialize(key),valueSerializer.serialize(value), SafeEncoder.encode("NX"),SafeEncoder.encode("EX"), Protocol.toByteArray(expire)); return null != object; }); return isSuccess; }  //释放锁 public boolean releaseLock(String key){ return redisTemplate.delete(key); }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: springboot redis分布式锁代码实例

以上就上有关springbootredis分布式锁代码实例的相关介绍,要了解更多springboot,redis,分布式锁内容请登录学步园。

抱歉!评论已关闭.