39 lines
1.2 KiB
Java
39 lines
1.2 KiB
Java
|
package com.atguigu.utils;
|
||
|
|
||
|
import com.alibaba.fastjson.JSON;
|
||
|
import com.atguigu.constant.MessageConstant;
|
||
|
import com.atguigu.constant.RedisUserConstant;
|
||
|
import com.atguigu.exception.BunnyException;
|
||
|
import com.atguigu.spzx.model.entity.user.UserInfo;
|
||
|
import org.apache.commons.lang.StringUtils;
|
||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||
|
import org.springframework.data.redis.core.RedisTemplate;
|
||
|
import org.springframework.stereotype.Component;
|
||
|
|
||
|
@Component
|
||
|
public class RedisUtils {
|
||
|
@Autowired
|
||
|
private RedisTemplate<String, Object> redisTemplate;
|
||
|
|
||
|
public static String getCartKey(Long userId) {
|
||
|
return RedisUserConstant.REDIS_CART_KEY + userId;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Redis通过token获取用户信息
|
||
|
*
|
||
|
* @param token 请求key的token
|
||
|
* @return 用户信息
|
||
|
*/
|
||
|
public UserInfo getUserInfo(String token) {
|
||
|
// 获取用户信息字符串
|
||
|
Object object = redisTemplate.opsForValue().get(token);
|
||
|
String jsonString = JSON.toJSONString(object);
|
||
|
if (StringUtils.isEmpty(jsonString)) {
|
||
|
throw new BunnyException(MessageConstant.USER_DOES_NOT_EXIST);
|
||
|
}
|
||
|
// 转为UserInfo类
|
||
|
return JSON.parseObject(jsonString, UserInfo.class);
|
||
|
}
|
||
|
}
|