package com.shanghaichengdi.ghjgitem.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shanghaichengdi.ghjgitem.service.RedisService;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisServiceImpl implements RedisService {

  private static final Logger log = LoggerFactory.getLogger(RedisServiceImpl.class);
  @Resource
  private RedisTemplate<String, Object> redisTemplate;


  @Override
  public boolean hasKey(String key) {
    return Boolean.TRUE.equals(redisTemplate.hasKey(key));
  }

  @Override
  public boolean hasKey(String folder, String key) {
    return Boolean.TRUE.equals(redisTemplate.hasKey(folder + key));
  }

  @Override
  public void setStringCache(String key, String value) {
    redisTemplate.opsForValue().set(key, value);
  }

  @Override
  public void setStringCache(String folder, String key, String value) {
    redisTemplate.opsForValue().set(folder + key, value);
  }

  @Override
  public void setStringCache(String key, String value, Integer time, TimeUnit timeUnit) {
    redisTemplate.opsForValue().set(key, value, time, timeUnit);
  }

  @Override
  public void setStringCache(String folder, String key, String value, Integer time,
      TimeUnit timeUnit) {
    redisTemplate.opsForValue().set(folder + key, value, time, TimeUnit.MINUTES);
  }

  @Override
  public String getValue(String key) {
    return (String) redisTemplate.opsForValue().get(key);
  }

  @Override
  public String getValue(String folder, String key) {
    return (String) redisTemplate.opsForValue().get(folder + key);
  }

  @Override
  public void deleteKeys(String prefix) {
    Set<String> keys = redisTemplate.keys(prefix + "*");
    log.info("删除掉的key有:{}", JSONObject.toJSONString(keys));
    redisTemplate.delete(keys);
  }
}
