软件编程
位置:首页>> 软件编程>> java编程>> springboot redis分布式锁代码实例

springboot redis分布式锁代码实例

作者:小白啊小白,Fighting  发布时间:2023-12-05 21:40:10 

标签:spring,boot,redis,分布式,锁

这篇文章主要介绍了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;

@Component
public 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);
 }
}

来源:https://www.cnblogs.com/ywjfx/p/12100817.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com