介绍
小编给大家分享一下复述分布式锁的实现示例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!
<强> Redisson 强>
<强> Redisson和下列一下自行封装两种方式的区别(场景):强>
- <李>
Redisson未获取到锁的会进入等待,直到获取到锁。
李> <李>另外两种方式如果未获取到锁,会放弃,不会执行业务代码。
李>& lt; dependency> ,,,& lt; groupId> org.redisson ,,,& lt; artifactId> redisson-spring-boot-starter ,,,& lt; version> 3.13.6 & lt;/dependency>
@Autowiredprivate Redisson redisson; @GetMapping (“/redissonLock") public String redissonLock (), { ,,,log.info(“进入了方法“); ,,,RLock lock =, redisson.getLock (“redissonLock"); ,,,try { ,,,,,,,lock.lock(30日,TimeUnit.SECONDS); ,,,,,,,thread . sleep (10000); ,,,,,,,System.out.println(“我是你大哥“); ,,,},catch (InterruptedException e), { ,,,,,,,e.printStackTrace (); ,,,},{finally ,,,//,如果不释放,不会唤起其他线程,则其他线程会超时过期自动唤醒,不会执行业务代码 ,,,,,,,lock.unlock (); ,,,} ,,,return “运行结束“;}
<强> RedisTemplate封装复述,锁(1)强>
& lt; dependency> ,,& lt; groupId> org.springframework.boot ,大敌;& lt; artifactId> spring-boot-starter-data-redis & lt;/dependency>
package com.util; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisStringCommands; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.data.redis.core.types.Expiration; import org.springframework.stereotype.Component; import java.util.Arrays; @Componentpublic class RedisLock { ,,,private static RedisTemplate redisTemplate; ,,,private static String script =,“if redis.call(\“\”,键[1]),==,ARGV[1],然后\ n" + ,,,,,,,,,,,“\ treturn redis.call(\“德尔\“键[1])\ n" + ,,,,,,,,,,,,其他\ n" + ,,,,,,,,,,,,,,,\ treturn 0 \ t \ n" + ,,,,,,,,,,,,最终获得,“; ,,,public RedisLock (RedisTemplate redisTemplate), { ,,,,,,,RedisLock.redisTemplate =, redisTemplate; ,,,} ,,,public static Boolean getLock (String 关键,String 价值,Long expireTime), { ,,,,,,,RedisStringCommands.SetOption setOption =, RedisStringCommands.SetOption.ifAbsent (); ,,,,,,,Expiration Expiration =, Expiration.seconds (expireTime); ,,,,,,,RedisCallback, booleanRedisCallback =, new RedisCallback (), { ,,,,,,,,,,@Override ,,,,,,,,,,,public Boolean doInRedis (RedisConnection 连接),throws DataAccessException { ,,,,,,,,,,,,,,,return connection.set (redisTemplate.getKeySerializer () .serialize(关键),redisTemplate.getValueSerializer () .serialize(价值),过期,,setOption); ,,,,,,,,,,,} ,,,,,,,}; ,,,,,,,return (布尔),redisTemplate.execute (booleanRedisCallback); ,,,} ,,,public static Boolean 解锁(String 关键,String 价值),{ null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null 复述分布式锁的实现示例