Jedis Use summary "Pipeline" "Distributed ID Generator" "Distributed lock" watch "" Multi "" "Redis distributed"

Source: Internet
Author: User

Prior to the details of the Jedis use, Jedis is the Java version of the Redis client implementation.
This article makes a summary, the main share the following content:

"Pipeline" "Distributed ID Generator" "Distributed lock" watch "" Multi "" "Redis distributed"
All right, one to one.
First, Pipeline
Official note: Starts a pipeline,which is a very efficient means to send lots of command and read all the responses when you finish Sending them. Simply put, pipeline is suitable for batch processing. Pipelines can be used when there are a large number of operations that need to be executed at once.
Example:
Jedis Jedis = new Jedis (String, int);
Pipeline p = jedis.pipelined ();
P.set (Key,value);//each operation sends a request to Redis-server
P.get (Key,value);

P.sync ();//This code gets all the response here I did 20w continuous operation (10w read, 10w write), without pipeline time: 187242ms, with pipeline time: 1188ms, It can be seen that the performance of the pipe after the use of a step. Read the code to understand that the pipeline passes a one-time write request and then reads the response once. That is to say Jedis is: request Response,request response, ... The pipeline is: Request request ... response response way. This eliminates the need for each request to wait for a server-side response.

Second, cross-JVM ID generator
When it comes to this topic, the first thing to know is that the redis-server side is single-threaded to handle client requests.
This makes it very easy to implement an ID generator, as long as you simply call JDEIS.INCR (key);
You may ask, INCR is atomic operation, can guarantee not to have concurrency problem, previously said, server side is single-threaded processing request.

"Watch" "Multi" for "lock across the JVM"
First of all, the use of this problem scenario, sometimes our business logic is in a different JVM process or even a different physical machine on the JVM processing. How to implement synchronization problems on different JVMs, we can actually implement a lock based on Redis.
For specific transactions and monitoring, please refer to the article: Redis Learning Notes Business
Find three ways to implement it temporarily:
1. Through Jedis.setnx (Key,value) to achieve
Import Java.util.Random;
Import Org.apache.commons.pool.impl.GenericObjectPool.Config;

Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;
Import redis.clients.jedis.Transaction;

/**
* @author Teaey
*/
public class Redislock {
Lock flag
public static final String LOCKED = "TRUE";
public static final Long One_milli_nanos = 1000000L;
Default time-out (milliseconds)
public static final long default_time_out = 3000;
public static Jedispool pool;
public static final Random r = new Random ();
Lock time-out (seconds), expired delete
public static final int EXPIRE = 5 * 60;
static {
Pool = new Jedispool (new Config (), "host", 6379);
}
Private Jedis Jedis;
Private String key;
Lock status Flag
Private Boolean locked = FALSE;

Public Redislock (String key) {
This.key = key;
This.jedis = Pool.getresource ();
}

Public boolean lock (long timeout) {
Long nano = System.nanotime ();
Timeout *= One_milli_nanos;
try {
while ((System.nanotime ()-Nano) < timeout) {
if (Jedis.setnx (key, LOCKED) = = 1) {
Jedis.expire (key, expire);
Locked = true;
return locked;
}
Short sleep, Nano avoids live lock
Thread.Sleep (3, R.nextint (500));
}
} catch (Exception e) {
}
return false;
}
public Boolean lock () {
return lock (Default_time_out);
}

Whether or not the lock is successful, you must call the
public void unlock () {
try {
if (locked)
Jedis.del (key);
} finally {
Pool.returnresource (Jedis);
}
}
}2. Implemented through transactions (multi)
With the adoption of the first method, the second and third implementation only put the key code, hope understanding. ^_^
public boolean lock_2 (long timeout) {Long nano = System.nanotime ();
Timeout *= One_milli_nanos;
try {
while ((System.nanotime ()-Nano) < timeout) {
Transaction t = Jedis.multi ();
Open transaction, when server side receives multi instruction
The client's commands are placed in a queue and then executed sequentially, knowing that the EXEC command was received
T.getset (key, LOCKED);
T.expire (key, expire);
string ret = (string) t.exec (). get (0);
if (ret = = NULL | | ret.equals ("UNLOCK")) {
return true;
}
Short sleep, Nano avoids live lock
Thread.Sleep (3, R.nextint (500));
}
} catch (Exception e) {
}
return false;
}3. Implemented through transaction + monitoring
public boolean lock_3 (long timeout) {Long nano = System.nanotime ();
Timeout *= One_milli_nanos;
try {
while ((System.nanotime ()-Nano) < timeout) {
Jedis.watch (key);
After watch is turned on, if the value of key is modified, the transaction fails, and the Exec method returns null
String value = Jedis.get (key);
if (value = = NULL | | value.equals ("UNLOCK")) {
Transaction t = Jedis.multi ();
T.setex (Key, EXPIRE, LOCKED);
if (t.exec () = null) {
return true;
}
}
Jedis.unwatch ();
Short sleep, Nano avoids live lock
Thread.Sleep (3, R.nextint (500));
}
} catch (Exception e) {
}
return false;
The first implementation is finally implemented because the locking only needs to send a single request, which is the most efficient.
Four, "Redis distributed"
The last topic, Jedis distributed. In the source code of Jedis found two hash algorithms (Md5,murmur hash (default)), can also implement their own redis.clients.util.Hashing interface extension.
List<jedisshardinfo> hosts = new arraylist<jedisshardinfo> (); Server1
Jedisshardinfo host1 = new Jedisshardinfo ("", 6380, 2000);
Server2
Jedisshardinfo host2 = new Jedisshardinfo ("", 6381, 2000);
Hosts.add (host1);
Hosts.add (HOST2);
Shardedjedis Jedis = new Shardedjedis (hosts);
Jedis.set ("Key", "");

Jedis Use summary "Pipeline" "Distributed ID Generator" "Distributed lock" watch "" Multi "" "Redis distributed"

Related Article

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.