Redis using Java script to implement distributed lock _redis

Source: Internet
Author: User
Tags eval lua redis

Redis is heavily used in distributed environments, and it becomes a problem to solve the locks in a distributed environment. For example, our current hand-travel program, server side is divided by Business module server, there are applications, combat clothing, etc., but these two VMS can also change the player's properties, which if under the same VM, it is easy to lock, but if in a distributed environment is not so easy, Of course, there are solutions to using Redis's existing functionality, such as Redis scripts.

Redis adds the functionality of the Lua script in later versions of 2.6, can execute LUA scripts directly in the Redisserver environment through the eval command, and can invoke the Redis command in the Lua script.
The benefits of using scripting:

1. Reduce network overhead: Some functions to be processed in batches can be executed in a script to reduce the number of interactions between client and Redis
2. Atomic operation: This is mainly the function we use here to ensure the atomicity of the data in a distributed environment.
3. Multiplexing: Client-sent scripts are stored permanently in Redis, which means that other clients can reuse the script without having to use code to complete the same logic.

Let's look at a section of the Lua script:

Copy Code code as follows:

Local Food=redis.call (' Hget ', keys[1], ' food ');
FOOD=FOOD+ARGV[1];
Redis.call (' Hset ', keys[1], ' food ', food);
Local Diamond=redis.call (' Hget ', keys[1], ' diamond ');
DIAMOND=DIAMOND+ARGV[2];
Redis.call (' Hset ', keys[1], ' Diamond ', diamond);

Note: Redis.call is that we call the Redis command in the script, the keys and the ARGV2 array, which are the keys and the parameters, the subscript all starting from 1, not 0.
The function of this script is to remove the player food (fodder) and diamond (Jade) specified by the keys, and then modify the row, and finally save it in Redis, the execution of the script, which guarantees the atomicity of the whole operation.

Here we use Java code to look at the specific implementation process

Copy Code code as follows:

Jedis Jedis = new Jedis ("192.168.128.128", 6379);
1. Initial player data to Redis
Gameplayer player = new Gameplayer ();
Player.setid (1001);
Player.setname ("Ksfzhaohui");
Player.setfood (100);
Player.setdiamond (100);

map<string, string> beanmap = beanutil.warp (player);//convert object to map
String Beankey = Getredisbeankey (Player.getclass (), Player.getid ());
System.out.println ("key:" + Beankey);
Jedis.hmset (Beankey, Beanmap)//Save player data to Redis

First simulates a player to save the player information in the Redis, this side of the ID casually wrote a, normal situation is through the Redis command INCR generate an ID
Results:

Copy Code code as follows:

String script = "Local Food=redis.call (' Hget ', keys[1], ' food ');"
+ "food=food+argv[1];"
+ "Redis.call (' Hset ', keys[1], ' food ', food);"
+ "Local Diamond=redis.call (' Hget ', keys[1], ' diamond ');"
+ "diamond=diamond+argv[2];"
+ "Redis.call (' Hset ', keys[1], ' Diamond ', diamond);";
list<string> keys = new arraylist<string> ();
Keys.add (Beankey);
list<string> args = new arraylist<string> ();
Args.add ("100");
Args.add ("100");
3. Execute script
Jedis.eval (script, keys, args);

Specify keys and references, execute scripts, and result:

Beanutil Code:

Copy Code code as follows:

public class Beanutil {
private static Logger Logger = Logger.getlogger (Beanutil.class);
private static final String class = "Class";

/**
* Encapsulates the specified object data into a map
*
* @param Bean
* Object Data
* @return
*/
@SuppressWarnings ("All")
public static map<string, string> warp (Object Bean) {
map<string, string> propertymap = new hashmap<string, string> ();
try {
Propertydescriptor[] PS = Introspector.getbeaninfo (Bean.getclass ())
. Getpropertydescriptors ();
for (PropertyDescriptor Propertydescriptor:ps) {
String propertyname = Propertydescriptor.getname ();
if (propertyname!= null &&!propertyname.equals (CLASS)) {
Method getter = Propertydescriptor.getreadmethod ();
if (getter!= null) {
Propertymap.put (PropertyName,
String.valueof (Getter.invoke (bean, null));
}
}
}
catch (Exception e) {
Logger.error (e);
}
return propertymap;
}

}

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.