In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
In this issue, the editor will bring you about the principle of redis to achieve distributed locks, analyze and describe it from a professional point of view. I hope you can get something after reading this article.
Distributed lock is a way to control synchronous access to shared resources between distributed systems.
In distributed systems, it is often necessary to coordinate their actions. If one or a group of resources are shared between different systems or different hosts of the same system, mutual exclusion is often needed to prevent interference from each other to ensure consistency when accessing these resources. distributed locks are needed.
Using four redis commands: setnx, getset, expire and del.
Setnx is an abbreviation for "SET if Not eXists" (or SET if it does not exist). Command format: SETNX key value; use: set the value of the key key to value only if the key key does not exist. If the key key already exists, the SETNX command does nothing. Return value: the command returns 1 when the setting is successful and 0 if the setting fails.
The getset command format: GETSET key value, sets the value of the key key to value and returns the old value of the key key before it was set. Return value: if the key key has no old value, that is, the key key does not exist before it is set, then the command returns nil. The command returns an error when the key key exists but is not a string type.
Expire command format: EXPIRE key seconds, use: set the time to live for a given key, when the key expires (time to live is 0), it will be automatically deleted. Return value: 1 is returned if the setting is successful. Return 0 when key does not exist or cannot set the lifetime for key (such as when you try to update the lifetime of key in versions earlier than 2.1.3 of Redis).
Del command format: DEL key [key...] Use: delete one or more given key, and key that does not exist will be ignored. Return value: the number of key deleted.
The principle of Redis to implement distributed lock:
1. Through setnx (lock_timeout), if the lock is set to return 1, a value that has not been set successfully returns 0
two。 Deadlock problem: determine whether it expires through practice. If it has expired, get the expiration time get (lockKey), and then getset (lock_timeout) determines whether it is the same as get. If it is the same, it proves that the lock has been successful, because it may cause multiple threads to execute the getset (lock_timeout) method at the same time, which may cause multiple threads to only need getset. Plus expire (lockKey, LOCK_TIMEOUT, TimeUnit.MILLISECONDS) expiration time to prevent multiple threads from superimposing time at the same time, resulting in double lock aging time
Code:
/ * * @ author yaoxin * @ date 5:04 on 2018-8-13 * / public class RedisLockTest {public static final String url = "jdbc:mysql://127.0.0.1:3306/ly?characterEncoding=UTF-8"; public static final String name = "com.mysql.jdbc.Driver"; public static final String user = "root"; public static final String password = ""; public static void main (String [] args) {Integer count = 50 While (count > 0) {count--; new Thread (new Runnable () {@ Override public void run () {Jedis jedis = new Jedis ("127.0.0.1", 6379); jedis.auth ("1234"); String lock = lock (jedis) If (lock! = null) {Statement statement = null; Connection conn = null; ResultSet resultSet = null; try {Class.forName (name) / / specify connection type conn = DriverManager.getConnection (url, user, password); / / get connection statement = conn.createStatement (); / / prepare to execute statement String querySql = "SELECT id,name,count FROM production WHERE id=2"; resultSet = statement.executeQuery (querySql) Int count = 0 While (resultSet.next ()) {System.out.println (Thread.currentThread (). GetName () + "grabbed the lock id:" + resultSet.getString ("id") + "name:" + resultSet.getString ("name") + "count:" + resultSet.getString ("count")) Count= Integer.valueOf (resultSet.getString ("count"));} String updateSql = "UPDATE production SET count=" + (count-1) + "WHERE id=2"; int rows = statement.executeUpdate (updateSql) If (rows > 0) {System.out.println ("updated successfully" + Thread.currentThread () .getName () + "inventory surplus:" + (count-1)); System.out.println (Thread.currentThread () .getName () + "= = > > start unlocking") Boolean unlock = unlock (jedis, lock); if (unlock) System.out.println (Thread.currentThread () .getName () + "= = > > unlocked successfully") } else {System.out.println ("update failed" + Thread.currentThread () .getName ());}} catch (Exception e) {e.printStackTrace () } finally {try {if (conn! = null) conn.close (); if (statement! = null) statement.close () If (resultSet! = null) resultSet.close ();} catch (Exception e) {e.printStackTrace () }}, "thread" + count) .start () } public static String lock (Jedis jedis) {try {while (true) {String lockTime = Long.valueOf (jedis.time (). Get (0)) + 5 + "; if (jedis.setnx (" lock ", lockTime) = = 1) {jedis.expire (" lock ", 5); return lockTime } String lock = jedis.get ("lock"); if (! StringUtils.isEmpty (lock) & & Long.valueOf (lock) < Long.valueOf (jedis.time (). Get (0)) {String oldLockTime = jedis.getSet ("lock", lockTime) If (! StringUtils.isEmpty (oldLockTime) & & oldLockTime.equals (lock)) {return lockTime;}} Thread.sleep;}} catch (Exception e) {e.printStackTrace ();} return null } public static boolean unlock (Jedis jedis, String lockTag) {if (lockTag.equals (jedis.get ("lock") {jedis.del ("lock"); return true;} return false;}}
The running result is as follows:
The above is the principle of implementing distributed locks in redis shared by Xiaobian. If you have similar doubts, you might as well refer to the above method to try. If you want to know more about it, please follow the industry information.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.