EF + Redis (StackExchange. Redis) implements distributed locks, which is feasible in self-testing. stackexchange. redis

Source: Internet
Author: User

EF + Redis (StackExchange. Redis) implements distributed locks, which is feasible in self-testing. stackexchange. redis

E-commerce platforms will have a flash sale, for example, 1 yuan flash sale. The most important thing about flash sales is inventory. In many cases, if the inventory is not properly processed, the oversold status may occur.

This article uses redis as the cache, StackExchange framework, and message queue to implement distributed locks

I. Results

First look at the effect,

 

High concurrency of form Order Construction

Open multiple console applications to process orders

2. Configure Redis

  <Redis.Service>    <DbConfig Name="Order_DBName"  Hosts="127.0.0.1:6379" dbNum="2">    </DbConfig>    <DbConfig Name="Product_DbName" Hosts="127.0.0.1:6379" dbNum="1">    </DbConfig>

Simulate user order

      private void button1_Click(object sender, EventArgs e)        {            var orderCount = Convert.ToInt32(txt_OrderCount.Text);            var productId = Convert.ToInt32(txt_ProductId.Text);            var productCount = Convert.ToInt32(txt_ProductCount.Text);            for (int i = 0; i < orderCount; i++)            {                RedisOrderModel cacheOrder = new RedisOrderModel()                {                    Count = productCount,                    OrderNo = (orderNo += 1).ToString(),                    ProductId = productId                };                orderRedis.Push(cacheOrder);            }                    }

Console program processing order

Public void QueueList () {RedisOrderMessage redis = new RedisOrderMessage (); while (true) {try {var cacheOrder = redis. pop (); if (cacheOrder = null) {Console. writeLine ("no order, rest 100 milliseconds"); Thread. sleep (1000); continue;} while (ThreadCount <= 0) {Console. writeLine ("the Thread is full and the rest is 100 milliseconds"); Thread. sleep (100);} // ThreadCount --; Thread thread = new Thread (new ThreadStart (cacheOrder. createOrder); thread. start (); Console. writeLine ("processing order, rest 100 milliseconds"); Thread. sleep (100);} catch (Exception ex) {Console. writeLine (ex. message + "," + ex. stackTrace); Thread. sleep (1000) ;}finally {ThreadCount ++ ;}}}

 

Use distributed locks to determine whether the inventory is sufficient

Public void LockStore (string productId, int count) {var keyInfo = AddSysCustomKey (productId); if (! Exists (keyInfo) {throw new Exception ("commodity cache does not exist");} var redisConfig = ReadRedisConfig. getRedisConfig (DB_Name); var lockdb = redisConfig. getDatabase (-1); var db = redisConfig. getDatabase (); var token = Environment. machineName; while (true) {// db. lockRelease (keyInfo, token); var con = lockdb. lockTake (keyInfo, token, TimeSpan. fromSeconds (10.0), CommandFlags. none); // var con = db. lockTake (keyInfo, token, TimeSpan. fromSeconds (20), CommandFlags. none); if (con) {try {var product = ConvertObj <CacheProduct> (db. stringGet (keyInfo); if (product. count <count) {throw new Exception ("insufficient quantity, order failed");} product. count-= count; var json = ConvertJson (product); db. stringSet (keyInfo, json);} finally {lockdb. lockRelease (keyInfo, token) ;}break ;}}}

Source Code address:

 

Https://github.com/buruainiaaaa/CacheDemo.git

 

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.