LockService.java 1.9 KB
Newer Older
ibiz4j's avatar
ibiz4j committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
package cn.ibizlab.util.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class LockService {


    @Autowired
    @Lazy
    private LockService proxy;

    @Cacheable( value="lock", key = "'key:'+#p0")
ibiz4j's avatar
ibiz4j committed
19
    public synchronized Long getLock(String key)
ibiz4j's avatar
ibiz4j committed
20
    {
ibiz4j's avatar
ibiz4j committed
21 22 23
        long lockTime=System.currentTimeMillis();
        System.out.println("lockTime"+lockTime);
        return lockTime;
ibiz4j's avatar
ibiz4j committed
24 25 26
    }

    @Cacheable( value="lock", key = "'key:'+#p0")
ibiz4j's avatar
ibiz4j committed
27
    public Long resetLock(String key,Long newLockTime)
ibiz4j's avatar
ibiz4j committed
28 29 30 31 32
    {
        return newLockTime;
    }

    @CacheEvict( value="lock", key = "'key:'+#p0")
ibiz4j's avatar
ibiz4j committed
33
    public void deleteLock(String key)
ibiz4j's avatar
ibiz4j committed
34 35 36 37
    {

    }

ibiz4j's avatar
ibiz4j committed
38
    public synchronized boolean isLocked(String key,Long lockTimeMillis)
ibiz4j's avatar
ibiz4j committed
39 40 41 42 43 44 45
    {
        if(StringUtils.isEmpty(key))
            return false;
        Long now=System.currentTimeMillis();

        Long lockTime=proxy.getLock(key);

ibiz4j's avatar
ibiz4j committed
46
        System.out.println(lockTime+":"+now);
ibiz4j's avatar
ibiz4j committed
47
        if(lockTime>=now)
ibiz4j's avatar
ibiz4j committed
48
            return false;
ibiz4j's avatar
ibiz4j committed
49

ibiz4j's avatar
ibiz4j committed
50
        if(lockTime+lockTimeMillis<now)
ibiz4j's avatar
ibiz4j committed
51 52 53 54 55 56 57 58 59 60 61 62 63
        {
            proxy.deleteLock(key);
            proxy.resetLock(key,now);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    proxy.resetLock(key,now);
                }
ibiz4j's avatar
ibiz4j committed
64 65
            }).start();
            return false;
ibiz4j's avatar
ibiz4j committed
66 67
        }

ibiz4j's avatar
ibiz4j committed
68
        return true;
ibiz4j's avatar
ibiz4j committed
69 70 71 72 73 74 75 76
    }

    public void unLock(String key)
    {
        proxy.deleteLock(key);
    }

}