package com.tzld.piaoquan.ad.engine.commons.redis;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class AdRedisHelper {
    private final static Logger log = LoggerFactory.getLogger(AdRedisHelper.class);

    @Resource(name = "adRedisTemplate")
    private RedisTemplate<String, String> adRedisTemplate;

    public Set<String> sMembers(String key) {
        return adRedisTemplate.opsForSet().members(key);
    }

    public boolean set(String key, String value, long time) {
        try {
            if (time > 0) {
                adRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                adRedisTemplate.opsForValue().set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error("adRedisHelper set error", e);
            return false;
        }
    }

    public String get(String key) {
        String val = adRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(val)) {
            return val;
        }
        return null;
    }

    public boolean del(String key) {
        return Boolean.TRUE.equals(adRedisTemplate.delete(key));
    }

    public boolean containsKey(String key) {
        return Boolean.TRUE.equals(adRedisTemplate.hasKey(key));
    }

    public List<String> mget(List<String> keys) {
        return adRedisTemplate.opsForValue().multiGet(keys);
    }

}
