- redis数据源接入
- redis缓存
- 用户登录标识缓存
- 访问接口权限拦截
用户登录标识缓存
TokenModel
/**
* @Author:Arthur Han
* @Description:
* @CreateDate:2017/3/2911:21
* @Modified By:
*/
public class TokenModel {
//用户id
private long userId;
//随机生成的uuid
private String token;
public TokenModel(long userId, String token) {
this.userId = userId;
this.token = token;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
RedisTokenManager
import arhur.test.domain.web.TokenModel;
/**
* @Author:Arthur Han
* @Description:
* @CreateDate:2017/3/2911:22
* @Modified By:
*/
public interface TokenManager {
/**
* 创建一个token关联上指定用户
* @param userId 指定用户的id
* @return 生成的token
*/
public TokenModel createToken(long userId);
/**
* 检查token是否有效
* @param model token
* @return 是否有效
*/
public boolean checkToken(TokenModel model);
/**
* 从字符串中解析token
* @param authentication 加密后的字符串
* @return
*/
public TokenModel getToken(String authentication);
/**
* 清除token
* @param userId 登录用户的id
*/
public void deleteToken(long userId);
}
RedisTokenManagerImpl
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import arthur.test.constant.RedisConstants;
import arthur.test.constant.WebConstants;
import arthur.test.domain.web.TokenModel;
import arthur.test.manager.TokenManager;
import arthur.test.redis.RedisClient;
import java.util.UUID;
/**
* @Author:Arthur Han
* @Description:
* @CreateDate:2017/3/2911:23
* @Modified By:
*/
@Component
public class RedisTokenManager implements TokenManager {
@Autowired
private RedisClient redis;
public TokenModel createToken(long userId) {
//使用uuid作为源token
String token = UUID.randomUUID().toString().replace("-", "");
TokenModel model = new TokenModel(userId, token);
//存储到redis并设置过期时间
redis.set(RedisConstants.PREFIX_USER+model.getUserId(),token);
redis.expire(RedisConstants.PREFIX_USER+model.getUserId(),WebConstants.TOKEN_EXPIRES);
return model;
}
public TokenModel getToken(String authentication) {
if (authentication == null || authentication.length() == 0) {
return null;
}
String[] param = authentication.split("_");
if (param.length != 2) {
return null;
}
long userId = Long.parseLong(param[0]);
String token = param[1];
return new TokenModel(userId, token);
}
public boolean checkToken(TokenModel model) {
if (model == null) {
return false;
}
String token = redis.get(RedisConstants.PREFIX_USER+model.getUserId());
if (token == null || !token.equals(model.getToken())) {
return false;
}
//如果验证成功,说明此用户进行了一次有效操作,延长token的过期时间
redis.expire(RedisConstants.PREFIX_USER+model.getUserId(), WebConstants.TOKEN_EXPIRES);
return true;
}
public void deleteToken(long userId) {
redis.del(RedisConstants.PREFIX_USER+userId);
}
}