package cn.com.qmth.examcloud.app.service; import cn.com.qmth.examcloud.app.core.utils.JsonMapper; import cn.com.qmth.examcloud.app.model.UserToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; import static cn.com.qmth.examcloud.app.model.Constants.REDIS_KEY_PREFIX; @Service public class RedisService { private static Logger log = LoggerFactory.getLogger(RedisService.class); @Autowired private StringRedisTemplate redisTemplate; public void set(String key, String value) { redisTemplate.opsForValue().set(key, value); } public void set(String key, String value, long seconds) { redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS); } public String get(String key) { return redisTemplate.opsForValue().get(key); } public boolean exist(String key) { return redisTemplate.hasKey(key); } public void delete(String key) { redisTemplate.delete(key); } public void cacheUserToken(String key, UserToken value, long seconds) { this.set(REDIS_KEY_PREFIX + key, new JsonMapper().toJson(value), seconds); } public UserToken getUserToken(String key) { String value = this.get(REDIS_KEY_PREFIX + key); if (value != null) { return new JsonMapper().fromJson(value, UserToken.class); } return null; } }