C # uses Redis to implement distributed locks

Source: Internet
Author: User

Redis has three of the most basic properties to ensure effective implementation of distributed locks:

    • Security: Mutex, at any time, only one client can hold a lock.
    • Active A: There is no deadlock, even if the client crashes while holding the lock, there will be other clients to obtain the lock, timeout mechanism.
    • Active B: Failure tolerance, only the majority of Redis nodes survive, the client can still get locks and release locks.

The use of Stackexchange.redis is easy to implement.

Static voidLock () {Console.WriteLine ("Start ... .."); vardb =_redis.            Getdatabase (); Redisvalue token=Environment.MachineName; //actual item seconds kill here can be replaced by Product ID            if(Db. Locktake ("Test", token, Timespan.fromseconds (Ten)))            {                Try{Console.WriteLine ("working ....."); Thread.Sleep ( the); }                finally{db. Lockrelease ("Test", token); }} Console.WriteLine ("Over ... .."); }

Last attached github address: Https://github.com/xiaopotian1990/RedisDemo

C # uses Redis to implement distributed locks

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.