项目结构
pom.xml
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-redis
1.4.5.RELEASE
com.alibaba
fastjson
1.2.31
nl.bitwalker
UserAgentUtils
1.2.4
commons-codec
commons-codec
1.6
application.properties
##指定使用redis数据库索引(默认为0)
spring.redis.database=0
##指定Redis服务器地址
spring.redis.host=192.168.126.149
##指定Redis端口号
spring.redis.port=6379
##指定Redis密码
spring.redis.password=123456
User.java
package com.fengqing.aapredis.bean;
public class User {
private Integer id;
private String username;
private String password;
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Dto.java
package com.fengqing.aapredis.bean;
public class Dto {
private String token;
private Long tokenCreatedDate;
private Long tokenExpiryDate;
private String isLogin;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Long getTokenCreatedDate() {
return tokenCreatedDate;
}
public void setTokenCreatedDate(Long tokenCreatedDate) {
this.tokenCreatedDate = tokenCreatedDate;
}
public Long getTokenExpiryDate() {
return tokenExpiryDate;
}
public void setTokenExpiryDate(Long tokenExpiryDate) {
this.tokenExpiryDate = tokenExpiryDate;
}
public String getIsLogin() {
return isLogin;
}
public void setIsLogin(String isLogin) {
this.isLogin = isLogin;
}
}
RedisConfig.java
package com.fengqing.aapredis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
RedisUtil.java
package com.fengqing.aapredis.util;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class RedisUtil {
@Resource
private RedisTemplate redisTemplate;
public void set(String key, String value) {
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set(key, value);
}
public void setex(String key, String value, int seconds) {
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set(key, value, seconds);
}
}
TokenService.java
package com.fengqing.aapredis.service;
import com.alibaba.fastjson.JSONObject;
import com.fengqing.aapredis.bean.User;
import com.fengqing.aapredis.util.RedisUtil;
import nl.bitwalker.useragentutils.UserAgent;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
@Service("tokenService")
public class TokenService {
@Resource
private RedisUtil redisUtil;
//生成token(格式为token:设备-加密的用户名-时间-六位随机数)
public String generateToken(String userAgentStr, String username) {
StringBuilder token = new StringBuilder("token:");
//设备
UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr);
if (userAgent.getOperatingSystem().isMobileDevice()) {
token.append("MOBILE-");
} else {
token.append("PC-");
}
//加密的用户名
token.append(DigestUtils.md5Hex(username) + "-");
//时间
token.append(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "-");
//六位随机字符串
token.append(new Random().nextInt(999999 - 111111 + 1) + 111111 );
System.out.println("token-->" + token.toString());
return token.toString();
}
//把token存到redis中
public void save(String token, User user) {
if (token.startsWith("token:PC")) {
redisUtil.setex(token, JSONObject.toJSONString(user), 2*60*60);
} else {
redisUtil.set(token, JSONObject.toJSONString(user));
}
}
}
UserService.java
package com.fengqing.aapredis.service;
import com.fengqing.aapredis.bean.User;
import org.springframework.stereotype.Service;
@Service("userService")
public class UserService {
public User login(String username, String password) {
if ("tom".equals(username) && "123".equals(password)){
return new User(1, "tom", "123");
} else {
return null;
}
}
}
UserController.java
package com.fengqing.aapredis.controller;
import com.alibaba.fastjson.JSONObject;
import com.fengqing.aapredis.bean.Dto;
import com.fengqing.aapredis.bean.User;
import com.fengqing.aapredis.service.TokenService;
import com.fengqing.aapredis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private TokenService tokenService;
@RequestMapping("/login")
@ResponseBody
public String login(String username, String password, HttpServletRequest request) {
Dto dto = new Dto();
User user = this.userService.login(username, password);
if (user != null) {
String userAgent = request.getHeader("user-agent");
String token = this.tokenService.generateToken(userAgent, username);
this.tokenService.save(token, user);
dto.setIsLogin("true");
dto.setToken(token);
dto.setTokenCreatedDate(System.currentTimeMillis());
dto.setTokenExpiryDate(System.currentTimeMillis() + 2*60*60*1000);
} else {
dto.setIsLogin("false");
}
return JSONObject.toJSONString(dto);
}
}