Springboot Integrated Redisson distributed lock

Source: Internet
Author: User
Tags auth

Original: https://www.cnblogs.com/yangzhilong/p/7605807.html

Official Document: Https://github.com/redisson/redisson/wiki/%E7%9B%AE%E5%BD%95

20180226 Update: Add the Trylock method, it is recommended to remove the Distributedlocker interface and its implementation class, directly injected into the Redisslockutil Redissonclient implementation class (simple but will lose the flexibility of the interface).

1, the reference Redisson Pom

<dependency>    <groupId>org.redisson</groupId>    <artifactid>redisson</ Artifactid>    <version>3.5.0</version></dependency>

2. Defining the interface definition class for lock

Import Java.util.concurrent.timeunit;import Org.redisson.api.rlock;public interface Distributedlocker {    RLock Lock (String lockkey);    Rlock Lock (String lockkey, int timeout);    Rlock Lock (String lockkey, timeunit Unit, int timeout);    Boolean Trylock (String lockkey, timeunit unit, int waitTime, int leasetime);    void unlock (String lockkey);    void unlock (Rlock lock);}

3. Lock interface Implementation Class

Import Org.redisson.api.rlock;import Org.redisson.api.redissonclient;import Java.util.concurrent.timeunit;public    Class Redissondistributedlocker implements Distributedlocker {private redissonclient redissonclient;        @Override Public Rlock Lock (String lockkey) {Rlock lock = Redissonclient.getlock (Lockkey);        Lock.lock ();    return lock;        } @Override Public Rlock lock (String lockkey, int leasetime) {Rlock lock = Redissonclient.getlock (Lockkey);        Lock.lock (Leasetime, timeunit.seconds);    return lock; } @Override Public Rlock lock (String lockkey, timeunit Unit, int timeout) {Rlock lock = redissonclient.g        Etlock (Lockkey);        Lock.lock (timeout, unit);    return lock; } @Override public boolean trylock (String lockkey, timeunit unit, int waitTime, int leasetime) {rlock lo        ck = Redissonclient.getlock (Lockkey);        try {return Lock.trylock (waitTime, leasetime, unit); } CATCH (Interruptedexception e) {return false;        }} @Override public void unlock (String lockkey) {Rlock lock = Redissonclient.getlock (Lockkey);    Lock.unlock ();    } @Override public void unlock (Rlock lock) {lock.unlock ();    } public void Setredissonclient (Redissonclient redissonclient) {this.redissonclient = redissonclient; }}

4. Redisson attribute Assembly class

Import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties (prefix = "    Redisson ") public class Redissonproperties {private int timeout = 3000;    Private String address;    private String password;        private int connectionpoolsize = 64;    private int connectionminimumidlesize=10;    private int slaveconnectionpoolsize = 250;    private int masterconnectionpoolsize = 250;    Private string[] sentineladdresses;    Private String Mastername;    public int gettimeout () {return timeout;    } public void SetTimeout (int timeout) {this.timeout = timeout;    } public int getslaveconnectionpoolsize () {return slaveconnectionpoolsize; } public void setslaveconnectionpoolsize (int slaveconnectionpoolsize) {this.slaveconnectionpoolsize = SlaveConn    Ectionpoolsize;    } public int getmasterconnectionpoolsize () {return masterconnectionpoolsize; } public void setmasterconnectionpoolsize (int masterconnectionpoolsize) {this.masterconnectionpoolsize = masterconnectionpoolsize;    } public string[] Getsentineladdresses () {return sentineladdresses; The public void setsentineladdresses (String sentineladdresses) {this.sentineladdresses = Sentineladdresses.split (    ",");    } public String Getmastername () {return mastername;    } public void Setmastername (String mastername) {this.mastername = Mastername;    } public String GetPassword () {return password;    } public void SetPassword (String password) {this.password = password;    } public String getaddress () {return address;    The public void setaddress (String address) {this.address = address;    } public int getconnectionpoolsize () {return connectionpoolsize;    } public void setconnectionpoolsize (int connectionpoolsize) {this.connectionpoolsize = ConnectionPoolSize;      } public int getconnectionminimumidlesize () {  return connectionminimumidlesize; } public void setconnectionminimumidlesize (int connectionminimumidlesize) {this.connectionminimumidlesize = con    Nectionminimumidlesize; }}

5, Springboot Automatic assembly class

Import Org.apache.commons.lang3.stringutils;import Org.redisson.redisson;import org.redisson.api.RedissonClient; Import Org.redisson.config.config;import Org.redisson.config.sentinelserversconfig;import Org.redisson.config.singleserverconfig;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.boot.autoconfigure.condition.conditionalonclass;import Org.springframework.boot.autoconfigure.condition.conditionalonproperty;import Org.springframework.boot.context.properties.enableconfigurationproperties;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.configuration;import Com.longge.lock.distributedlocker;import Com.longge.lock.redissondistributedlocker;import Com.longge.lock.redissonproperties;import com.longge.utils.RedissLockUtil; @Configuration @conditionalonclass ( Config.class) @EnableConfigurationProperties (redissonproperties.class) public class Redissonautoconfiguration {@ autowired Private RedissonpropErties redssionproperties; /** * Sentinel Mode Automatic assembly * @return * * @Bean @ConditionalOnProperty (name= "Redisson.master-name") redissonclient        Redissonsentinel () {config config = new Config (); Sentinelserversconfig serverconfig = Config.usesentinelservers (). Addsentineladdress (                Redssionproperties.getsentineladdresses ()). Setmastername (Redssionproperties.getmastername ()) . SetTimeout (Redssionproperties.gettimeout ()). Setmasterconnectionpoolsize (Redssionproperties.getmastercon                Nectionpoolsize ()). Setslaveconnectionpoolsize (Redssionproperties.getslaveconnectionpoolsize ()); if (Stringutils.isnotblank (Redssionproperties.getpassword ())) {Serverconfig.setpassword (redssionPropertie        S.getpassword ());    } return Redisson.create (config);  */** * Automatic assembly Mode * @return * * * @Bean @ConditionalOnProperty (name= "redisson.address") redissonclient  Redissonsingle () {      Config config = new config ();                Singleserverconfig serverconfig = Config.usesingleserver (). Setaddress (Redssionproperties.getaddress ()) . SetTimeout (Redssionproperties.gettimeout ()). Setconnectionpoolsize (Redssionproperties.getconne                Ctionpoolsize ()). Setconnectionminimumidlesize (Redssionproperties.getconnectionminimumidlesize ()); if (Stringutils.isnotblank (Redssionproperties.getpassword ())) {Serverconfig.setpassword (RedssionPropert        Ies.getpassword ());    } return Redisson.create (config); }/** * Assemble the locker class and inject the instance into the redisslockutil * * @return * * * @Bean distributedlocker Distributedlocker (Redis        Sonclient redissonclient) {distributedlocker locker = new Redissondistributedlocker ();        Locker.setredissonclient (redissonclient);        Redisslockutil.setlocker (Locker);    return locker; }}

6. Lock Help Class

Import Java.util.concurrent.timeunit;import org.redisson.api.rlock;import distributedlocker;/** * Redis Distributed Lock helper class * @        Author Yangzhilong * */public class Redisslockutil {private static Distributedlocker redisslock;    public static void Setlocker (Distributedlocker locker) {redisslock = locker; }/** * Lock * @param lockkey * @return * * public static Rlock lock (String lockkey) {retur    n Redisslock.lock (Lockkey); }/** * Release lock * @param lockkey */public static void Unlock (String lockkey) {redisslock.unlock (loc    Kkey);     }/** * Release lock * @param lock */public static void Unlock (Rlock lock) {Redisslock.unlock (lock); /** * Lock with timeout * @param lockkey * @param timeout time-Out unit: SEC/public static Rlock lock (String l    Ockkey, int timeout) {return redisslock.lock (Lockkey, timeout); /** * Lock with timeout * @param lockkey * @param unit time unit * @param timesOut Timeout time */public static Rlock lock (String lockkey, timeunit Unit, int timeout) {return Redisslock.lock (lo    Ckkey, Unit, timeout);      }/** * Try to acquire lock * @param lockkey * @param waitTime maximum wait time * @param leasetime automatically release lock time after lockout * @return */public static Boolean Trylock (String lockkey, int waitTime, int leasetime) {return Redisslock.trylock (l    Ockkey, Timeunit.seconds, WaitTime, leasetime); /** * Try to acquire the lock * @param lockkey * @param unit time Unit * @param waitTime maximum wait time * @param leasetime Auto-release lock time after lock * @return */public static Boolean Trylock (String lockkey, timeunit unit, int waitTime, int leasetime    ) {return Redisslock.trylock (Lockkey, Unit, WaitTime, leasetime); }}

Properties File instance:

1. Stand-alone mode

# Redisson Lockredisson.address=redis://10.18.75.115:6379redisson.password=

If you do not add the redis://prefix, the URI build error will be reported.

caused By:java.net.URISyntaxException:Illegal character in Scheme name at index 0

Second, the Auth checksum fails if the password is not null-judged when Redis is connected.

caused By:org.redisson.client.RedisException:ERR client sent AUTH, but no password is set. Channel

2. Sentinel Mode

redisson.master-name=mymasterredisson.password=xxxxredisson.sentinel-addresses= 10.47.91.83:26379,10.47.91.83:26380,10.47.91.83:26381

More configuration information can go to the official website to view

Springboot Integrated Redisson distributed lock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.