/* * ************************************************* * Copyright (c) 2018 QMTH. All Rights Reserved. * Created by Deason on 2018-07-31 17:53:48. * ************************************************* */ package cn.com.qmth.examcloud.app.service; import cn.com.qmth.examcloud.app.core.exception.ApiException; import cn.com.qmth.examcloud.app.core.utils.JsonMapper; import cn.com.qmth.examcloud.app.core.utils.ThreadUtils; import cn.com.qmth.examcloud.app.model.Constants; 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.RedisTemplate; 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.APP_SESSION_USER_KEY_PREFIX; /** * Redis接口服务类 * * @author: fengdesheng * @since: 2018/7/16 */ @Service public class RedisService { private static Logger log = LoggerFactory.getLogger(RedisService.class); @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; public void set(String key, String value) { stringRedisTemplate.opsForValue().set(key, value); } public void set(String key, String value, long seconds) { stringRedisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS); } public String get(String key) { return stringRedisTemplate.opsForValue().get(key); } public boolean exist(String key) { return stringRedisTemplate.hasKey(key); } public void delete(String key) { stringRedisTemplate.delete(key); } /** * 缓存用户登录信息 */ public void cacheUserToken(String key, UserToken value, long seconds) { if (key == null) { throw new ApiException("Key must be not null."); } this.set(APP_SESSION_USER_KEY_PREFIX + key, new JsonMapper().toJson(value), seconds); } /** * 获取缓存中的用户登录信息 */ public UserToken getUserToken(String key) { if (key == null) { throw new ApiException("Key must be not null."); } String value = this.get(APP_SESSION_USER_KEY_PREFIX + key); if (value != null) { return new JsonMapper().fromJson(value, UserToken.class); } return null; } /** * 初始化内部接口鉴权 */ public void initTraceRequest() { String key = "C_" + ThreadUtils.getTraceID(); Long millis = System.currentTimeMillis(); this.set(key, millis.toString(), 10); } /** * 获取平台端的默认过期时间(秒) */ public int getSessionTimeout() { try { String timeout = this.get(Constants.PLATFORM_SESSION_TIMEOUT_KEY); if (timeout != null) { return Integer.parseInt(timeout); } } catch (Exception e) { //ignore } return Constants.PLATFORM_SESSION_EXPIRE_TIME; } }