LOADING

加载过慢请开启缓存 浏览器默认开启

Redis分布式锁

2023/8/14 Redis

'image-20221205205344611'

'image-20221205205724504'

Long userid = UserHolder.getUser().getId();

SimpleRedisLock lock = new SimpleRedisLock(StringRedisTemplate, "order:" + userid);
boolean trylock = lock.trylock(5L);

if (!trylock){
    Result.fail("不能重复下单!");
}

try {
    IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();//获取spring代理的类来保证事务的可用
    return proxy.createVoucherorder(voucherId);
} finally {
    lock.unLock();
}

'image-20221206161640611'

public interface ILock {

    public boolean trylock(Long timeoutSec);

    public void unLock();
}
public class SimpleRedisLock implements ILock{
    StringRedisTemplate StringRedisTemplate;
    String name;

    public SimpleRedisLock(org.springframework.data.redis.core.StringRedisTemplate stringRedisTemplate, String name) {
        StringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    private static final String KEY_PREFIX= "lock:";
    private static final String ID_PREFIX= UUID.randomUUID().toString(true)+"-";


    @Override
    public boolean trylock(Long timeoutSec) {
        String id = ID_PREFIX+Thread.currentThread().getId();
        Boolean aBoolean = StringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX+name,id,timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(aBoolean);
    }

    @Override
    public void unLock() {
        String threadId = ID_PREFIX + Thread.currentThread().getId();

        String id = StringRedisTemplate.opsForValue().get(KEY_PREFIX + name);

        if (threadId.equals(id)){
            StringRedisTemplate.delete(KEY_PREFIX+name);
        }

    }
}

'image-20221206162911007'

'image-20221206163433982'

'image-20221206163744785'

'image-20221206172143558'

'image-20221206172224025'

'image-20221206172441072'

'image-20221206173950087'

'image-20221206175321134'

'image-20221206181100353'

'image-20221206181232698'

'image-20221212133612546'

'image-20221212133548479'

'image-20221212133705487'

总结

'image-20221212131513937'