RedisService.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package cn.com.qmth.examcloud.app.service;
  2. import cn.com.qmth.examcloud.app.core.utils.JsonMapper;
  3. import cn.com.qmth.examcloud.app.model.UserToken;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.data.redis.core.StringRedisTemplate;
  8. import org.springframework.stereotype.Service;
  9. import java.util.concurrent.TimeUnit;
  10. import static cn.com.qmth.examcloud.app.model.Constants.REDIS_KEY_PREFIX;
  11. @Service
  12. public class RedisService {
  13. private static Logger log = LoggerFactory.getLogger(RedisService.class);
  14. @Autowired
  15. private StringRedisTemplate redisTemplate;
  16. public void set(String key, String value) {
  17. redisTemplate.opsForValue().set(key, value);
  18. }
  19. public void set(String key, String value, long seconds) {
  20. redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
  21. }
  22. public String get(String key) {
  23. return redisTemplate.opsForValue().get(key);
  24. }
  25. public boolean exist(String key) {
  26. return redisTemplate.hasKey(key);
  27. }
  28. public void delete(String key) {
  29. redisTemplate.delete(key);
  30. }
  31. public void cacheUserToken(String key, UserToken value, long seconds) {
  32. this.set(REDIS_KEY_PREFIX + key, new JsonMapper().toJson(value), seconds);
  33. }
  34. public UserToken getUserToken(String key) {
  35. String value = this.get(REDIS_KEY_PREFIX + key);
  36. if (value != null) {
  37. return new JsonMapper().fromJson(value, UserToken.class);
  38. }
  39. return null;
  40. }
  41. }