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

Introduction and example of redis Lock Mechanism

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

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

1 pessimistic lock

Assume that the current operation is certain (or likely) to be interrupted (pessimistic) before performing the operation. Based on this assumption, we lock the relevant resources before doing the operation, and do not allow other operations to interfere with our execution.

Redis does not support pessimistic locks. When Redis is used as a cache server, it is mainly read operations, few write operations, and the corresponding operations are less likely to be interrupted. Pessimistic locks are not used to prevent performance degradation.

2 optimistic lock

Assume that the current operation will not be interrupted before performing the operation (optimistic). Based on this assumption, we will not lock the resource before doing the operation, and this operation will be abandoned in case of interference from other operations.

3. Lock policy in Redis

Redis adopts an optimistic locking strategy (via watch operation). Optimistic lock supports read operation, which is suitable for more reading and less writing!

In a transaction, locks can be added through the watch command; locks can be unlocked using UNWATCH

If WATCH (lock) is executed before the transaction, the lock pair is automatically released after the EXEC command or DISCARD command is executed, that is, no more UNWATCH is required

Examples

Redis Lock tool Class

Package com.fly.lock;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class RedisLock {/ / initialize redis pool private static JedisPoolConfig config; private static JedisPool pool; static {config = new JedisPoolConfig (); config.setMaxTotal (30); config.setMaxIdle (10); pool = new JedisPool (config, "192.168.233.200", 6379) } / * lock target * @ param target * * / public static void lock (Object target) {/ / get jedis Jedis jedis = pool.getResource (); / / result receives the return value of setnx with an initial value of 0 Long result= 0L; while (result)

< 1) { //如果target在redis中已经存在,则返回0;否则,在redis中设置target键值对,并返回1 result = jedis.setnx(target.getClass().getName() + target.hashCode(), Thread.currentThread().getName()); } jedis.close(); } /** * 给target解锁 * @param target **/ public static void unLock(Object target) { Jedis jedis = pool.getResource(); //删除redis中target对象的键值对 Long del = jedis.del(target.getClass().getName() + target.hashCode()); jedis.close(); } /** * 尝试给target上锁,如果锁成功返回true,如果锁失败返回false * @param target * @return **/ public static boolean tryLock(Object target) { Jedis jedis = pool.getResource(); Long row = jedis.setnx(target.getClass().getName() + target.hashCode(), "true"); jedis.close(); if (row >

0) {return true;} return false;}}

Test class

Package com.fly.test;import com.fly.lock.RedisLock;class Task {public void doTask () {/ / lock RedisLock.lock (this); System.out.println ("current thread:" + Thread.currentThread (). GetName ()); System.out.println ("start execution:" + this.hashCode ()); try {System.out.println ("doing..."); Thread.sleep (2000) } catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("done:" + this.hashCode ()); / / unlock RedisLock.unLock (this);}} public class Demo {public static void main (String [] args) {Task task = new Task (); Thread [] threads = new Thread [5] For (Thread thread: threads) {thread = new Thread (()-> {task.doTask ();}); thread.start ();}}

Output result:

-

Current thread: Thread-0

Start execution: 2081499965

Doing...

Complete: 2081499965

-

Current thread: Thread-2

Start execution: 2081499965

Doing...

Complete: 2081499965

-

Current thread: Thread-1

Start execution: 2081499965

Doing...

Complete: 2081499965

-

Current thread: Thread-4

Start execution: 2081499965

Doing...

Complete: 2081499965

-

Current thread: Thread-3

Start execution: 2081499965

Doing...

Complete: 2081499965

After the redis lock is removed, the execution result:

-

-

Current thread: Thread-2

Start execution: 1926683415

-

Current thread: Thread-1

Doing...

Current thread: Thread-0

-

Current thread: Thread-3

Start execution: 1926683415

Doing...

Start execution: 1926683415

Doing...

-

Start execution: 1926683415

Doing...

Current thread: Thread-4

Start execution: 1926683415

Doing...

Complete: 1926683415

Complete: 1926683415

Complete: 1926683415

Complete: 1926683415

Complete: 1926683415

Process finished with exit code 0

Using the nature of redis, you can achieve distributed locks, of course, the design must be a little more complicated!

Summary

The above is the whole content of this article. I hope the content of this article has a certain reference and learning value for everyone's study or work. Thank you for your support. If you want to know more about it, please see the relevant links below.

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

Database

Wechat

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

12
Report