Redis simple implementation of a distributed lock

/ ** 
 * This Controller simulates after a reduction of purchases of goods scene, realized by a distributed lock Redis, 
 * solve the oversold appear at high concurrency scenarios in distributed applications, repeated selling problem, this idea can be applied in a variety of scenarios 
 can use the * actual development Redisson achieve Redis distributed lock, the idea is not resolved Redis master-slave replication, host downtime can cause 
 * LockKey loss problem, Redis official offers RedLock to solve this problem, specific self-understanding 
 * 
 * @author Mr.Don 
 * 
 * / 
@RestController 
public  class blockTestController { 

    // distinguished server Nginx currently selected by the port number of the returned 
    @Value ( "the server.port $ {}" )
     Private String port; 

    @Autowired 
    Private stringRedisTemplate StringRedisTemplate; 

    @RequestMapping ( "/ Test" )
     public String Test () {
            UUID String = UUID.randomUUID () toString ();. 
            String lockKey = "lockKey" ;
             the try {
             // by circulating the request does not get the lock has been trying to acquire the lock 
            the while ( to true ) {
                 / * 
                 * Use setnx disposed LockKey, when LockKey set successfully, returns to true, 
                 * when there are other requests has been set LockKey false returns, must, have already acquired a lock (set LockKey) of 
                 (LockKey delete settings) * after the request to release the lock and then acquires the lock 
                 * / 
                boolean = stringRedisTemplate.opsForValue Result () setIfAbsent (lockKey, UUID, 10. , TimeUnit.SECONDS);
                 IF (Result) {
                     / *
                     * This thread is to solve the after LockKey set the expiration time, if the request expired in LockKey 
                     not complete a program execution * after, it will cause the current request has not yet released the lock, there are other requests to obtain a lock 
                     * eventually lead to unsafe thread may lead to premature failure of the lock, so after a request to acquire the lock, it will start a separate thread 
                     * the thread to create a scheduled task on a regular basis to renew the locks, timed task execution period is less than the expiration time LockKey, 
                     * more specific time with business requirements set, Redisson frame also realized renewal function 
                     * / 
                    new new the Thread () {
                         public  void RUN () {
                             new new the Timer (). Schedule ( new new the TimerTask () { 
                                @Override 
                                public  void RUN () { 
                                    stringRedisTemplate. The expire (lockKey, 10, TimeUnit.SECONDS);
                                     // determine whether the current request to release a lock if the lock is released, on this request for renewal is turned off 
                                    IF .! (StringRedisTemplate.opsForValue () GET (lockKey) = uuid)
                                         the this .cancel () ; 
                                } 
                            }, 5000, 5000 ); 
                        } 
                    } .start (); 
                    BREAK ; 
                } 
            } 
            // have Redis server in a data num Key, the number of analog to commodities 
            . String value = stringRedisTemplate.opsForValue () get ( "NUM" );
             int NUM = Integer.parseInt(value);
            if (num <= 0) {
                System.out.println("库存不足");
            } else {
                System.out.println("库存数量: "+num--);
                stringRedisTemplate.opsForValue().set("num", String.valueOf(num));
            }
        } finally {
            stringRedisTemplate.delete(lockKey);
        }
        return "port: " + port;

    }
}

 

Guess you like

Origin www.cnblogs.com/tcsjava/p/11346695.html