package com.sonic.bear.config;

import com.sonic.common.utils.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 有关Redis的配置
 *
 * TODO: 如果不需要Redis, 可以删除该文件并且在{@link Config}类@Import的注解中移除对RedisConfig的引用
 */
@Slf4j
public class RedisConfig {

    /**
     * redisWrapper用于分布式锁RedisLock
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    RedisLock.RedisWrapper redisWrapper(RedisTemplate redisTemplate) {
        return new RedisLock.RedisWrapper() {
            @Override
            public void delete(String key) {
                redisTemplate.delete(key);
            }

            @Override
            public boolean lock(String key, String value, long expireMills) {
                return redisTemplate.opsForValue().setIfAbsent(key, value, expireMills, TimeUnit.MILLISECONDS);
            }
        };
    }

}
