package com.lxzn.auth;
|
|
import com.alibaba.fastjson.JSON;
|
import com.lxzn.framework.domain.auth.ext.AuthToken;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
import org.springframework.stereotype.Component;
|
|
import java.util.concurrent.TimeUnit;
|
|
/**
|
* @author: zzx
|
* @date: 2018/10/23 10:31
|
* @description: redis工具类
|
*/
|
@Component
|
@Slf4j
|
public class RedisUtil {
|
|
//@Value("${auth.tokenValiditySeconds}")
|
private int tokenValiditySeconds = 1200;
|
|
@Autowired
|
private StringRedisTemplate redisTemplate;
|
|
//用户存储token的前缀
|
public static final String USER_TOKEN_PRE = "user_token:";
|
|
/**
|
* 存储到令牌到redis
|
* @param access_token 用户身份令牌
|
* @param content 内容就是AuthToken对象的内容
|
* @return
|
*/
|
public boolean saveToken(String access_token,String content){
|
return saveToken(access_token, content, tokenValiditySeconds);
|
}
|
/**
|
* 存储到令牌到redis
|
* @param access_token 用户身份令牌
|
* @param content 内容就是AuthToken对象的内容
|
* @param ttl 过期时间
|
* @return
|
*/
|
public boolean saveToken(String access_token,String content, long ttl){
|
String key = USER_TOKEN_PRE + access_token;
|
redisTemplate.boundValueOps(key).set(content, ttl, TimeUnit.SECONDS);
|
Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
|
return expire>0;
|
}
|
|
/**
|
* 删除redis中的令牌
|
* @param access_token
|
* @return
|
*/
|
public boolean delToken(String access_token){
|
String key = USER_TOKEN_PRE + access_token;
|
redisTemplate.delete(key);
|
return true;
|
}
|
|
|
//从redis查询令牌
|
public AuthToken getUserToken(String token){
|
String key = USER_TOKEN_PRE + token;
|
//从redis中取到令牌信息
|
String value = redisTemplate.opsForValue().get(key);
|
//转成对象
|
try {
|
AuthToken authToken = JSON.parseObject(value, AuthToken.class);
|
return authToken;
|
} catch (Exception e) {
|
log.error(e.getMessage(), e.getStackTrace());
|
return null;
|
}
|
|
}
|
|
|
}
|