Correct posture for Redis distributed locks

Source: Internet
Author: User
Tags redis uuid
1. Demand Analysis

The author's project has a check-in function: A user can only sign in once a day, but in the case of concurrency, a user may be able to check in several times a day, in this case, the first thing I think of is the use of Redis distributed lock to solve the problem 2.redis distributed lock

The setnx in ①redis has a natural locking mechanism; If a key exists in the Redis, it returns 0, the store fails, or 1 is returned, and the storage is successful;

② getting the correct posture for Redis distributed locks

private static final String lock_success = "OK";
private static final String set_if_not_exist = "NX";
private static final String Set_with_expire_time = "PX";
private static final Long release_success = 1L;
public static Boolean Trygetdistributedlock (Jedis Jedis, String Lockkey, string requestid, int expiretime) {
   string re Sult = Jedis.set (Lockkey, RequestID, Set_if_not_exist, Set_with_expire_time, expiretime);

   System.out.println ("============= acquires distributed lock result:" +result);

   if (lock_success.equals (Result)) {
      return true;
   }
   return false;
}

It also sets the expire time for Redis, when a Linux server crashes or Redis collapses, without a deadlock, and key is automatically deleted after the expiration time. In this case, the setting of the storage and expiration time of key is atomic, which effectively avoids the previous deadlock.

③ the wrong way to get a distributed lock

Shardedjedis Shardedjedis = Redisclientutil.getshardedjedis ();
Long update =  shardedjedis.setnx ("goods", "n");
SYSTEM.OUT.PRINTLN ("Storage success:" +update);
Shardedjedis.expire ("goods", +);  30-second Expiration Time
shardedjedis.close ();

In this case, if the system is down or crashes, then the distributed lock is likely to become a deadlock, adding to the pressure of Redis, after all, the setting of the storage and expiration time of the key is non-atomic operation;

④ correct posture for releasing distributed locks

/**
 * Release distributed lock
  Jedis
 lockkey
 requestid
 @return
  *
/public static Boolean Releasedistributedlock (Jedis Jedis, String Lockkey, String RequestID) {

   string Script = "If Redis.call (' Get ', keys[1]) = = Argv[1] then return Redis.call (' del ', Keys[1]) else return 0 end";
   Object result = jedis.eval (script, Collections.singletonlist (Lockkey), Collections.singletonlist (RequestID));

   if (release_success.equals (Result)) {
      return true;
   }
   return false;

}
2. Example Use

① in the case of concurrency, sign-in repetition


② distributed locking solves this concurrency problem correctly

Redis distributed lock Jedis Jedis = Redisclientutil.getjedis ();
Boolean flag = Redisclientutil.trygetdistributedlock (Jedis, "Singlock:" +userid,userid,1 * 60 * 1000);

Jedis.close (); if (flag) {//Gets the distributed lock succeeded String Registrationid = this.equipmentMapper.findRegistrationId ("UserId"). ToString (
));
Sign in random red envelopes BigDecimal signredpacketnum = new BigDecimal (Redpacketutil.randompacketbysign ());
Employees random Red envelope BigDecimal signfullredpacket = new BigDecimal (Redpacketutil.randompacketbysignfull ());
int totaldays = Dateutil.gettoaldaynow ();
Integer signdaynum = This.signMapper.findsignDayNum (params);
Sign todaysign = this.signMapper.findTodaySign (params);
Sign in red envelopes map<string,string> pushmap=new hashmap<> ();
Pushmap.put ("Redpactetid", Params.get ("uuid"));
Pushmap.put ("Packetamount", String.valueof (Signredpacketnum));
Pushmap.put ("Type", "2018");
Pushmap.put ("Packettype", "3");

Pushmap.put ("Packetbody", "Sign in red envelopes");
Employees Red Envelope map<string,object> redpacketfullmaps = new hashmap<> (); Redpacketfullmaps.put("UUID", Params.get ("uuid"));
Redpacketfullmaps.put ("userid", Params.get ("userid"));
Redpacketfullmaps.put ("Packetamount", Signfullredpacket);
Redpacketfullmaps.put ("Packettype", 4);

Redpacketfullmaps.put ("Packetbody", "Congratulations you get a sign employees red envelope");
Map<string,string> pushsignmap=new hashmap<> ();
Pushsignmap.put ("Redpactetid", Params.get ("uuid"));
Pushsignmap.put ("Packetamount", Double.tostring (Signfullredpacket.doublevalue ()));
Pushsignmap.put ("Type", "2019");
Pushsignmap.put ("Packettype", "4");

Pushsignmap.put ("Packetbody", "Employees red Envelopes");
hashset<string> registrationids = new hashset<> ();

    Registrationids.add (Registrationid);
    if (todaysign! = null) {return resultjsonutil.tofailurejsonstring (today_is_signed); }//Check if (Params.get ("type"). Equals ("1")) {Integer repairsignnum = this.signMapper.findRepairSignNum (par
        AMS);

            if (Repairsignnum < 2) {this.signMapper.userSign (params); Return resultjsonutil.tosuccessjsonstring(UUID);
        } else {return resultjsonutil.tofailurejsonstring (month_two);
    }}//Sign-in String Signordercode = Randomcodeutil.getordercode (paytypeconfig.yivi_user_sign);

    Employees String Fullordercode = Randomcodeutil.getordercode (paytypeconfig.yivi_user_full_sign);
        if (Params.get ("type"). Equals ("0") && todaysign = = null) {this.signMapper.userSign (params);
        This.redPacketMapper.putRedPacket (Redpacketmaps);
        Add System wallet pipelining record Double sysremainamount = This.accountMapper.findSysAmountByUserId (Alipayutil.yivi_system_account); Accountflow Sysflow = Accountflow.newbuilder (). Setuserid (Alipayutil.yivi_system_account). SetOrderCode (SignOrderCo
                de). Setbody ("red envelope Expense"). Setisinflow ("0"). SetType ("3"). Settotal_amount (Signredpacketnum.tostring ())
        . Setremainamount (Sysremainamount.tostring ()). build (); Integer Insertsysaccountflow = This.accountFlowMapper.insertSysFlow (Sysflow.tomap ());
        try {pushthreadpool.getinstance (). Push (Pushdatamodel.redpacketsend (Pushmap, registrationids), Channa
        L);
        } catch (Exception e) {e.printstacktrace ();
            } if (totaldays-signdaynum.intvalue () = = 1) {redpacketmapper.putredpacket (redpacketfullmaps); Accountflow sysflowfull = Accountflow.newbuilder (). Setuserid (Alipayutil.yivi_system_account). SetOrderCode (FullOrd
                    ErCode). Setbody ("red envelope Expense"). Setisinflow ("0"). SetType ("3"). Settotal_amount (Signfullredpacket.tostring ())
            . Setremainamount (Sysremainamount.tostring ()). build ();
            This.accountFlowMapper.insertSysFlow (Sysflowfull.tomap ());
        Pushthreadpool.getinstance (). Push (Pushdatamodel.redpacketsend (Pushsignmap, Registrationids), channal); }
    }
}

The author of the user's userid as a key, each user with a own distributed lock key, and key expiration time set to 1 minutes, so in a minute of time, concurrency is not possible, and so key failure and then access, the system will be thrown "today you have checked in" The Warm reminder

All right, I'm Zhang Xing Zhaoyuan. Welcome to the BO Master Technology Exchange Group, Group No.: 313145288

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.