Locks are a basic service for many systems, but implementing a lock on a distributed environment is not a simple matter. Fortunately now all kinds of components complete, today we introduce the Redis-based lock Java implementation-redssion. (Redis-based SETNX native implementation of distributed locks: http://blog.csdn.net/wwd0501/article/details/79472511) 1. Installing Redis
Installation of Redssion's lock service team Redis version is required and requires that the JDK 1.6+ be higher than the 2.8 version. For the installation of Redis, the description is not included here. 2.redssion Library
Add the Pom file to the Redssion library.
<dependency>
<groupId>org.redisson</groupId>
<artifactid>redisson</ artifactid>
<version>2.2.8</version>
</dependency>
3. Test examples
Config config = new config ();
Config.usesingleserver (). Setaddress ("ipaddress:6379");
Redissonclient Redisson = redisson.create (config);
Rlock lock = Redisson.getlock ("Testlock");
try{ //Support expired unlock function, automatically unlock after 10 seconds, no need to call the Unlock method to manually unlock
lock.lock (10,timeunit.seconds);
SYSTEM.OUT.PRINTLN ("test");
} finally{
Lock.unlock ();
Redisson.shutdown ();
}
Note: After using Redisson, it is important to remember to call the shutdown () method to close, however, in the actual project development call shutdown method, time consuming more than 2s, so shutdown method can not be used in the formal project, but do not call shutdown method Close, A request for a connection, the connection does not shut down, the server connection resources are easily exhausted and in suspended animation, so the best way to implement Redisson instance sharing. Here's how:
Import Org.redisson.Config;
Import Org.redisson.Redisson;
Import org.redisson.RedissonClient;
Import Org.redisson.core.RLock;
/**
* Distributed Lock Tool class */public
class Rlockutil {public
static redissonclient Redisson = null;
Static {
config config = new Config ();
Config.usesingleserver (). Setaddress ("Ipaddress:port");
Redisson = redisson.create (config);
}
public static Rlock Getlock (String lockname) {
rlock lock = null;
if (Redisson! = null) {
lock = Redisson.getlock (Lockname);
}
return lock;
}
}
Redisson Original Address: Https://github.com/mrniko/redisson
Redisson part of the Data translation address: http://ifeve.com/redis-lock/
Reference article: https://www.jianshu.com/p/cde0700f0128