java redis 实现简单的用户签到功能

业务需求是用户每天只能签到一次,而且签到后用户增加积分,所以把用户每次签到时放到redis 缓存里面,然后每天凌晨时再清除缓存,大概简单思想是这样的 

直接看代码吧如下 

@Transactional
 @Override
 public void signIn(Integer memberId) throws BizException {
  if(memberId==null){
   throw new BizException(ErrorCode.BIZ_EXCEPTION.getErrcode(), "签到用户id 不能为null");
  }
  String day = DateFormatUtils.format(new Date(), "yyyyMMdd");
  String key = "signin:"+day;
  Boolean sismember = redisClient.sismember(key, memberId.toString());
  if(sismember){
   throw new BizException(ErrorCode.BIZ_EXCEPTION.getErrcode(), "今天已经签到了");
  }else{
   redisClient.sadd(key, memberId.toString());
   redisClient.expire(key, getRefreshTime());
   addPointsRecord(memberId,IntegralType.SIGN_IN);//给用户增加积分
  }
  
 }

获取离凌晨 还有多久

/**
  * 获取当前时间离明天凌晨还有多少小时
  * @return
  */
 public static int getRefreshTime(){
  Calendar calendar = Calendar.getInstance();
  int now = (int) (calendar.getTimeInMillis()/1000);
  calendar.add(Calendar.DATE, 1);
  calendar.set(Calendar.SECOND, 0);
  calendar.set(Calendar.MINUTE, 0);
  calendar.set(Calendar.HOUR_OF_DAY , 0);
  return (int) (calendar.getTimeInMillis()/1000-now);
 }

Controller 

/**
  * 签到
  * @return
  */
 @WeiXinLogin
 @RequestMapping("/signIn")
 public ResponseModel signIn(){
  try {
   Integer memberId = RequestContext.getContext().getUser().getMemberId();
   memberApi.signIn(memberId);
   return new ResponseModel();
  } catch (BizException e) {
   LOGGER.error("signIn error");
   return new ResponseModel(e.getErrcode(), e.getErrm(), null);
  }
 }

以上就是java redis 实现简单的用户签到功能的详细内容,更多关于Java 实现用户签到功能的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(java redis 实现简单的用户签到功能)