作者 朱兆平

add: 用户心跳在线保持功能

1. 数据库增加了字段
2. users对象增加字段.
3. 缓存增加key
... ... @@ -7,6 +7,7 @@ import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.thoughtworks.xstream.core.util.Base64Encoder;
import com.tianbo.warehouse.controller.response.ResultJson;
import com.tianbo.warehouse.model.ROLE;
import com.tianbo.warehouse.model.Token;
import com.tianbo.warehouse.service.RoleService;
import com.tianbo.warehouse.util.RedisUtils;
... ... @@ -74,7 +75,7 @@ public class AnonymousController {
String verifyToken = "";
try {
verifyToken = UUID.randomUUID().toString();
redisUtils.set("verifyToken:" + verifyToken,String.valueOf(sum),1200);
redisUtils.set(Token.VERIFY_TOKEN_KEY + verifyToken,String.valueOf(sum),1200);
ImageIO.write(bi, "jpeg", outputStream);
map.put("verifyImg","data:image/jpeg;base64,"+encoder.encode(outputStream.toByteArray()));
} catch (IOException e) {
... ...
package com.tianbo.warehouse.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tianbo.warehouse.controller.response.ResultJson;
import com.tianbo.warehouse.dao.USERSMapper;
import com.tianbo.warehouse.model.Token;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.util.RedisUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
@RestController()
@Slf4j
public class HeartBeatController {
@Autowired
private RedisUtils redisUtils;
@Resource
private USERSMapper usersMapper;
//检查token时效是否低于标准线
static final long TOKEN_TTL_CHECK_MIN= 36000L;
//重置token时效为标准线
static final long TOKEN_TTL_ADD= 86400L;
//心跳每次续费时长
static final long HEARTBEAT_TOKEN_TTL_ADD= 10L;
@ApiOperation(value = "用户心跳接口", notes = "心跳续期")
@PostMapping("/heartbeat")
public ResultJson heartbeat(HttpServletRequest request, HttpServletResponse response){
try {
//1. 获取客户端IP,因为有反向代理所以要从头部获取代理过来的头部IP
String clientIP =null;
clientIP = request.getRemoteAddr();
String header_forwarded = request.getHeader("x-forwarded-for");
if (StringUtils.isNotBlank(header_forwarded)) {
clientIP = request.getHeader("x-forwarded-for");
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
if (clientIP.contains(",")) {
clientIP = clientIP.split(",")[0];
}
}
//2.获取token
String token = request.getHeader("Authorization");
/**
* key样式
* accessToken:token
*/
if (token!=null && !token.isEmpty() && token.startsWith(Token.VERIFY_TOKEN_TYPE)){
token = token.substring(Token.VERIFY_TOKEN_TYPE.length());
String accessToken = token;
String userDetailStr = redisUtils.get(accessToken);
//4. 更新用户心跳时间及在线状态IP等资料
if (StringUtils.isNotBlank(userDetailStr)){
JSONObject u = JSON.parseObject(userDetailStr);
Integer userId= u.getInteger("userId");
String username = u.getString("username");
/**3.续期token过期时间
* 增加过期时间,考虑到程序及网络传输中间的时间损耗,
* 每10秒一个的心跳直接续费10秒的话,token的过期时间还是会随着时间逐步减少
*/
long tokenExpireTime= redisUtils.getExpire(accessToken);
if(tokenExpireTime < TOKEN_TTL_CHECK_MIN){
redisUtils.expire(accessToken, TOKEN_TTL_ADD);
redisUtils.expire(Token.USER_TOKEN_KEY+username, TOKEN_TTL_ADD);
}else{
redisUtils.expire(accessToken,tokenExpireTime+HEARTBEAT_TOKEN_TTL_ADD);
redisUtils.expire(Token.USER_TOKEN_KEY+username, tokenExpireTime+HEARTBEAT_TOKEN_TTL_ADD);
}
USERS user = new USERS();
user.setUserId(userId);
user.loginIp = clientIP;
user.loginDate = new Date();
//1 为在线状态
user.setUserStatus(1);
int i = usersMapper.updateByPrimaryKeySelective(user);
return i > 0 ? new ResultJson("200","心跳成功"): new ResultJson("400","心跳失败");
}
}
return new ResultJson("400","心跳失败");
}catch (Exception e){
log.error("[HEART-BEAT-ERROR]-",e);
return new ResultJson("400","心跳失败");
}
}
}
... ...
... ... @@ -24,6 +24,8 @@ public interface USERSMapper {
List<USERS> selectAllUser(USERS users);
List<USERS> selectOnlineUser();
USERS getUserDataPermissionsByPath(@Param("userId") Integer userId,@Param("path") String path);
}
... ...
package com.tianbo.warehouse.heartbeat;
import com.tianbo.warehouse.dao.USERSMapper;
import com.tianbo.warehouse.model.USERS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
@Component
@Slf4j
public class OfflineTheardJob implements Runnable {
private static OfflineTheardJob offlineTheardJob;
private USERS user;
//用户掉线判定时间差
static final long OFFLINE_= 120L;
@Resource
private USERSMapper userMapper;
OfflineTheardJob() {
}
OfflineTheardJob(USERS user) {
this.user = user;
}
@PostConstruct
public void init(){
offlineTheardJob = this;
}
@Override
public void run(){
Date userLoginTime = user.loginDate;
if(userLoginTime!=null){
long diff= Math.abs(System.currentTimeMillis() - userLoginTime.getTime());
long s = diff / 1000;
log.info("[HEAT-BEAT]-用户{}心跳-时间相差{}秒",user.getUsername(),s);
if (s > OFFLINE_){
setOffline();
}
}else {
setOffline();
}
}
private void setOffline(){
user.setUserStatus(2);
int i = offlineTheardJob.userMapper.updateByPrimaryKeySelective(user);
if (i>0){
log.info("用户id:{},用户名称:{},从IP:{}掉线",user.getUserId(),user.getUsername(),user.loginIp);
}
}
}
... ...
package com.tianbo.warehouse.heartbeat;
import com.tianbo.warehouse.dao.USERSMapper;
import com.tianbo.warehouse.model.USERS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 清理心跳超时的在线用户,判定为离线
* @author xyh
* @date
* 记得给用户ID,用户名称,用户心跳时间,用户登录ip,用户在线状态的数据库字段设置索引。
*/
@Slf4j
@Component
public class OfflineUserTask {
@Resource
private USERSMapper userMapper;
@Scheduled(fixedRate = 60000)
private void offlineUserHeartBeat(){
//初始化线程池
ThreadPoolExecutor threadPool = XMLThreadPoolFactory.instance();
List<USERS> userList = userMapper.selectOnlineUser();
if (userList!=null && !userList.isEmpty()){
log.trace("用户掉线判定开始,共需判定{}个在线标识用户",userList.size());
for (USERS user:userList) {
OfflineTheardJob offlineTheardJob = new OfflineTheardJob(user);
threadPool.execute(offlineTheardJob);
}
}
}
}
... ...
package com.tianbo.warehouse.heartbeat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadFactory;
public class XMLThreadFactory implements ThreadFactory {
private int counter;
private String name;
private List<String> stats;
public XMLThreadFactory(String name)
{
counter = 1;
this.name = name;
stats = new ArrayList<String>();
}
@Override
public Thread newThread(Runnable runnable)
{
Thread t = new Thread(runnable, name + "-Thread_" + counter);
counter++;
stats.add(String.format("Created thread %d with name %s on %s \n", t.getId(), t.getName(), new Date()));
return t;
}
public String getStats()
{
StringBuffer buffer = new StringBuffer();
Iterator<String> it = stats.iterator();
while (it.hasNext())
{
buffer.append(it.next());
}
return buffer.toString();
}
}
... ...
package com.tianbo.warehouse.heartbeat;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class XMLThreadPoolFactory {
private static ThreadPoolExecutor threadPool;
public static ThreadPoolExecutor instance(){
if (threadPool==null){
XMLThreadFactory xmlThreadFactory = new XMLThreadFactory("heartbeatTask");
threadPool = new ThreadPoolExecutor(12, 128,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(2048),
xmlThreadFactory,
new ThreadPoolExecutor.AbortPolicy());
}
return threadPool;
}
}
... ...
package com.tianbo.warehouse.model;
public class Token {
public static String USER_TOKEN_KEY = "user:";
public static String VERIFY_TOKEN_KEY = "verifyToken:";
public static String VERIFY_TOKEN_TYPE = "Bearer ";
}
... ...
... ... @@ -58,6 +58,14 @@ public class USERS implements UserDetails {
private String token;
private Integer userStatus;
public String loginIp;
public Date loginDate;
public String createBy;
//用户所属企业ID,企业ID为用户绑定的组织机构顶层parentid为0的组织机构ID
private Integer companyId;
private String companyName;
... ... @@ -219,6 +227,14 @@ public class USERS implements UserDetails {
this.token = token;
}
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
public Integer getCompanyId() {
return companyId;
}
... ... @@ -258,7 +274,12 @@ public class USERS implements UserDetails {
*/
@Override
public boolean isAccountNonLocked(){
return true;
if (state){
return true;
}else {
return false;
}
}
/**
... ...
... ... @@ -3,6 +3,7 @@ package com.tianbo.warehouse.security.handel;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tianbo.warehouse.bean.AuthSuccessResponse;
import com.tianbo.warehouse.model.Token;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.security.config.SecurityProperties;
import com.tianbo.warehouse.security.filter.JwtTokenUtil;
... ... @@ -52,6 +53,7 @@ public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticat
RedisUtils redisUtils;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
int expirationSeconds = 3600*24*7;
logger.info("登录成功");
if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
//将 authention 信息打包成json格式返回
... ... @@ -77,7 +79,8 @@ public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticat
loginedUser.setToken(jwtToken);
//这里将登录成功的[user]对象数据写入redis缓存,KEY为token value为user的JSON对象
String json = JSON.toJSONString(user);
redisUtils.set(jwtToken, json,3600*24*7);
redisUtils.set(jwtToken, json,expirationSeconds);
redisUtils.set(Token.USER_TOKEN_KEY + user.getUsername(),jwtToken,expirationSeconds);
Map<String,Object> menuMap = permissionService.getUserMenus(user.getUserId());
//返回用户信息和用户可访问的目录列表
response.getWriter().write(objectMapper.writeValueAsString(new AuthSuccessResponse(loginedUser,menuMap)));
... ...
package com.tianbo.warehouse.security.login;
import com.tianbo.warehouse.model.Token;
import com.tianbo.warehouse.security.handel.MyAuthenticationFailHandler;
import com.tianbo.warehouse.security.handel.MyAuthenticationSuccessHandler;
import com.tianbo.warehouse.util.RedisUtils;
... ... @@ -58,7 +59,7 @@ public class MyLoginAuthenticationProcessFilter extends AbstractAuthenticationPr
//验证码判断
String verify = "";
verify = redisUtils.get("verifyToken:" + verifyToken);
verify = redisUtils.get(Token.VERIFY_TOKEN_KEY + verifyToken);
if(verify != null && loginVerify != null && verify.equals(loginVerify)){
authRequest = new UsernamePasswordAuthenticationToken(loginUserName,loginUserPass, null);
... ...
... ... @@ -17,6 +17,10 @@
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="company_id" property="companyId" jdbcType="INTEGER" />
<result column="user_status" property="userStatus" jdbcType="INTEGER" />
<result column="login_ip" property="loginIp" jdbcType="VARCHAR" />
<result column="login_date" property="loginDate" jdbcType="TIMESTAMP" />
<result column="create_by" property="createBy" jdbcType="VARCHAR" />
</resultMap>
<resultMap id="SecurityResult" type="com.tianbo.warehouse.model.USERS">
<id column="user_id" property="userId" jdbcType="INTEGER" />
... ... @@ -102,10 +106,12 @@
<sql id="Base_Column_List" >
user_id, username, password, birthday, sex, address, state, mobilePhone, creatTime,
updateTime, userFace, realName, email, age,company_id
updateTime, userFace, realName, email, age, company_id,
user_status, login_ip, login_date, create_by
</sql>
<sql id="user_List" >
user_id, username, birthday, sex, address, state, mobilePhone,userFace, realName, email, age
user_id, username, birthday, sex, address, state, mobilePhone,userFace, realName, email, age,
user_status, login_ip, login_date, create_by
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
... ... @@ -155,12 +161,13 @@
realName,
email,
age,
company_id,
company_id,user_status, login_ip, login_date, create_by,
r.role_id,role_name,role_sign,r.description AS rdescription,`type`,parentId,rsort,customs_reg_code,business_license,departmentId,mq_code
FROM
(
SELECT
user_id,username,birthday,sex,address,state,mobilePhone,creatTime,updateTime,userFace,realName,email,age,company_id
user_id,username,birthday,sex,address,state,mobilePhone,creatTime,updateTime,userFace,realName,email,age,company_id,
user_status, login_ip, login_date, create_by
FROM users
<where>
<if test=" username != null and username != ''" >
... ... @@ -186,12 +193,12 @@
birthday, sex, address,
state, mobilePhone, creatTime,
updateTime, userFace, realName,
email, age)
email, age,create_by)
values (#{userId,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{birthday,jdbcType=TIMESTAMP}, #{sex,jdbcType=CHAR}, #{address,jdbcType=VARCHAR},
#{state,jdbcType=BIT}, #{mobilephone,jdbcType=VARCHAR}, #{creattime,jdbcType=TIMESTAMP},
#{updatetime,jdbcType=TIMESTAMP}, #{userface,jdbcType=VARCHAR}, #{realname,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
#{email,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},#{createBy,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.tianbo.warehouse.model.USERS" >
insert into users
... ... @@ -241,6 +248,9 @@
<if test="companyId != null" >
company_id,
</if>
<if test="createBy != null" >
create_by,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="userId != null" >
... ... @@ -288,6 +298,9 @@
<if test="companyId != null" >
#{companyId,jdbcType=INTEGER},
</if>
<if test="createBy != null" >
#{createBy,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.USERS" >
... ... @@ -332,6 +345,12 @@
<if test="companyId != null" >
company_id = #{companyId,jdbcType=INTEGER},
</if>
<if test="userStatus != null" >
user_status = #{userStatus,jdbcType=INTEGER},
</if>
<if test="loginDate != null" >
login_date = #{loginDate,jdbcType=TIMESTAMP},
</if>
</set>
where user_id = #{userId,jdbcType=INTEGER}
</update>
... ... @@ -365,4 +384,11 @@
and path = #{path,jdbcType=VARCHAR}
and dp.perm_status = 0
</select>
<select id="selectOnlineUser" resultMap="BaseResultMap" >
select
<include refid="Base_Column_List" />
from users
where user_status = 1;
</select>
</mapper>
... ...