package com.freemud.sdk.api.assortment.order.util;

import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author haibo.jiang
 * @Description:
 * @date 2019/11/6 14:38
 */
public class LockUtils {

    private static String redis_lock_after="saas:lockAfter:";

    public static Boolean lockAfter(RedisTemplate redisTemplate,String afterId){
        return lock(redisTemplate,redis_lock_after+afterId);
    }

    private static boolean lock(RedisTemplate redisTemplate,String key){
        String lock =  key;
        // 利用lambda表达式
        return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
            long expireAt = 300;
            Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());

            if (acquire) {
                connection.expire(lock.getBytes(),expireAt);
                return true;
            } else {
                return false;
            }
        });
    }

}
