Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement distributed Lock with redis

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

After ii uses watch:

② uses Lua script

Redis can guarantee the atomicity of code execution through the eval command

Java configuration class:

Package com.lau.boot_redis01.util;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class RedisUtil {private static JedisPool jedisPool; static {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig (); jedisPoolConfig.setMaxTotal (20); jedisPoolConfig.setMaxIdle (10); jedisPool = new JedisPool (jedisPoolConfig, "127.0.0.1", 6379Jue 100000) } public static Jedis getJedis () throws Exception {if (nullable jewelry) {return jedisPool.getResource ();} throw new Exception ("Jedispool is not ok");}} Jedis jedis = RedisUtil.getJedis () String script = "if redis.call ('get', KEYS [1]) = = ARGV [1]" + "then" + "return redis.call (' del', KEYS [1])" + "else" + "return 0" + "end"; try {Object result = jedis.eval (script, Collections.singletonList (REDIS_LOCK), Collections.singletonList (value)) If ("1" .equals (result.toString () {System.out.println ("- del REDIS_LOCK_KEY success");} else {System.out.println ("- del REDIS_LOCK_KEY error") }} finally {if (null! = jedis) {jedis.close ();}} 8, still existing problems (redisson solved)

How do I renew ① Redis distributed locks? The problem of ensuring that the redisLock expiration time is greater than the business execution time (lock renewal)

② redis single point of failure-lock loss caused by redis asynchronous replication, for example, if the master node does not arrive and the data just set is sent to the slave node, it will fail. (zk/cp, redis/ap) (redis cluster)

The problem of ensuring that the expiration time of redisLock is greater than the business execution time. In the redis cluster environment, what we write is not OK, but directly implement it on the Redisson of RedLock.

1 、 RedisConfig.java

@ Bean public Redisson redisson () {Config config = new Config (); config.useSingleServer () .setAddress ("redis://" + redisHost+ ": 6379") .setDatabase (0); return (Redisson) Redisson.create (config);}

2. Controller class:

Package com.lau.boot_redis01.controller;import com.lau.boot_redis01.util.RedisUtil;import lombok.val;import org.redisson.Redisson;import org.redisson.RedissonLock;import org.redisson.api.RLock;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import redis.clients.jedis.Jedis Import java.util.Collections;import java.util.UUID;import java.util.concurrent.TimeUnit;@RestControllerpublic class GoodController_Redisson {@ Autowired private StringRedisTemplate stringRedisTemplate; @ Value ("${server.port}") private String serverPort; private static final String REDIS_LOCK = "atguigulock"; @ Autowired private Redisson redisson @ GetMapping ("/ buy_goods2") public String buy_Goods () throws Exception {String value = UUID.randomUUID (). ToString () + Thread.currentThread (). GetName (); RLock lock = redisson.getLock (REDIS_LOCK); try {lock.lock (); String result = stringRedisTemplate.opsForValue (). Get ("goods:001"); int goodsNumber = result = null? 0: Integer.parseInt (result) If (goodsNumber > 0) {int realNumber = goodsNumber-1; stringRedisTemplate.opsForValue (). Set ("goods:001", realNumber + "); System.out.println (" you have successfully killed the product, at this time there is still: + realNumber + "piece" + "\ t server port:" + serverPort) Return "you have successfully killed the merchandise, and there is still left:" + realNumber + "piece" + "\ t server port:" + serverPort;} System.out.println ("merchandise has been sold out / activity ends / call timeout, welcome to visit" + "\ t server port:" + serverPort) Return "merchandise has been sold out / activity ends / call timed out. Welcome to" + "\ t server port next time:" + serverPort;} finally {/ / IllegalMonitorStateException:attempt unlock lock,not locked by current thread by node_id if (lock.isLocked () & & lock.isHeldByCurrentThread ()) {lock.unlock ();}

Note: this kind of error may be encountered when there is too much concurrency and may be re-preempted.

At this point, I believe you have a deeper understanding of "how to use redis to achieve distributed locks". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report