[Share] new dream teacher Distributed Lock correct "posture"

I. Overview


In today's high concurrency, distributed popular today, if you have only single project, it would be too outdated. Leaving aside the outdated technology, the subject of ridicule outside (thick-skinned people do not care ridiculed), more realistic question is: If you are just entering the job market newcomer, will face to find a job, estimated that even interview had no chance; if you are already people serving, unaware distributed various adult posture, then you only fancy playing in the company's part. Speaking distributed so important, that I, as a veteran lurking IT circles for many years, to share with you today distributed under lock distributed under various postures adult, adults pay attention Oh, minors not to enter.


Second, the problem spot reduction - under the single spike system function


1.mysql database has two tables: stock (inventory table), stock_order (order form).


2. Background boot constructed single service interface (- orders - stock orders flow = Save check stock) by spring.


3. Open a browser normal business processes reproduction, refresh how many times, how many copies sell preserved egg porridge, no problems.




4. Use pressure measuring tool (ab / jemter / loaderrunner) pressure test ab -n 100 -c 100 http://127.0.0.1:8080/second-kill3/skill/order/123456


5. Open the browser again to see inventory




Tell me what you see this result is not a place to have a broken egg feeling! ! ! How could 10,000 copies preserved egg porridge can sell (9989 + 109), if you feel strange, you're already out of the technology. Well, this scene to restore to this end. Next to introduce you to a variety of positions at solving this problem.


Third, a posture: synchronized


Understanding Multithreaded students will certainly think, concurrent threads safety issues can be resolved with jdk synchronization tools synchronized. The right to say to you under correction, called the lost database updates. Can think here I will make it a little social practice posture, but how effective, see:


1. A method for single plus synchronized, synchronization do.




2. Continue stress test


ab -n 100 -c 100 http://127.0.0.1:8080/second-kill3/skill/order/123456




3.synchronized posture Summary:


1) is a solution.


2) synchronized unable to achieve fine-grained locks.


The method of adding synchronized the next one will have to do a single sync all goods, if another piece of merchandise is not very high concurrency. It can lead to very slow request, the lock size is too large.


3) only suitable for single-point situation. (The reality is that high concurrency, distributed clusters in power)


Fourth, the posture II: Distributed Lock


Next is our hero: Distributed Lock debut.


Implementation within Distributed Lock: distributed database lock, redis distributed lock, zookeeper distributed lock. Today intends to introduce under implementation redis distributed lock.


1. Install redis [I do not know how to install, please consult my official secretary of Mother]


Import 2.maven project in spring-redis dependence.


org.springframework.boot


spring-boot-starter-data-redis


3. Write redisLock achieve locking and unlocking


org.springframework.boot spring-boot-starter-data-redis


3. Write redisLock achieve locking and unlocking


/**


Lock


@param key


@param value the current time + time-out


@return


*/


public static boolean lock (String key ,String value){


// setIfAbsent = setNX If not, the value is set and returns true, false returns NO


//1,加锁成功 if(redisTemplate.opsForValue().setIfAbsent(key,value)){ return true; }


// 2, to avoid deadlock (1 thread lock is successful, the results appear abnormal, do not unlock Unlock the front, leading to a deadlock)


//2.1 get expiration time StringcurrentValue = redisTemplate.opsForValue () get (key).;


//2.2 judge expiration of the time at the current time


if(!StringUtils.isEmpty(currentValue)


&&Long.parseLong(currentValue)<System.currentTimeMillis()){String oldValue = redisTemplate.opsForValue().getAndSet(key,value); if(!StringUtils.isEmpty(oldValue)&&oldValue.equals(currentValue)){return true;


}


}


// 3, the end of the lock failure t2 returns false


return false;


}


/**


Unlock


@param key


@param value


*/


public void unLock(String key,String value){


try {


String currentValue = redisTemplate.opsForValue().get(key);


if(!StringUtils.isEmpty(currentValue)&&currentValue.equals(value)){


redisTemplate.opsForValue().getOperations().delete(key);


}


}catch (Exception e){


log.error ( "[] redis Distributed Lock Unlock exception");


}


}


4. The method of single locking, unlocking


@Override


public void orderProductMockDiffUser(String productId) throws Exception {


// [lock]


long time = System.currentTimeMillis()+TIMEOUT;


if(!redisLock.lock(productId,String.valueOf(time))){


throw new Exception ( "too many people, and in another position to try ~ ~ ~ ~");


}


// 1. The merchandise inventory query, the event is 0


int stockNum = stock.get(productId);


if(stockNum==0){


throw new Exception ( "end activity");


}else{


// 2. Orders (to simulate different users different openid)


orders.put(KeyUtil.genUniqueKey(),productId);


// 3. Less inventory


stockNum-=1;


try {


Thread.sleep(100);


}catch (Exception e){


e.printStackTrace ();


}


stock.put(productId,stockNum);


}


// 3. Unlock


redisLock.unLock(productId,String.valueOf(time));


}


5.redis posture Summary:


1) Small lock granularity. (Multiple items at the same time spike will not block)


2) for high concurrency, distributed cluster deployment.


Well, today's content to this end, we want to understand Distributed Lock helpful.


Guess you like

Origin blog.51cto.com/14627097/2461389