lyh
5 天以前 fda571324684bc8d0945b3e2841305b1207fc3e9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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;
        }
 
    }
 
 
}