java redis 实现简单的用户签到功能
业务需求是用户每天只能签到一次,而且签到后用户增加积分,所以把用户每次签到时放到redis缓存里面,然后每天凌晨时再清除缓存,大概简单思想是这样的
直接看代码吧如下
@Transactional @Override publicvoidsignIn(IntegermemberId)throwsBizException{ if(memberId==null){ thrownewBizException(ErrorCode.BIZ_EXCEPTION.getErrcode(),"签到用户id不能为null"); } Stringday=DateFormatUtils.format(newDate(),"yyyyMMdd"); Stringkey="signin:"+day; Booleansismember=redisClient.sismember(key,memberId.toString()); if(sismember){ thrownewBizException(ErrorCode.BIZ_EXCEPTION.getErrcode(),"今天已经签到了"); }else{ redisClient.sadd(key,memberId.toString()); redisClient.expire(key,getRefreshTime()); addPointsRecord(memberId,IntegralType.SIGN_IN);//给用户增加积分 } }
获取离凌晨还有多久
/** *获取当前时间离明天凌晨还有多少小时 *@return */ publicstaticintgetRefreshTime(){ Calendarcalendar=Calendar.getInstance(); intnow=(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") publicResponseModelsignIn(){ try{ IntegermemberId=RequestContext.getContext().getUser().getMemberId(); memberApi.signIn(memberId); returnnewResponseModel(); }catch(BizExceptione){ LOGGER.error("signInerror"); returnnewResponseModel(e.getErrcode(),e.getErrm(),null); } }
以上就是javaredis实现简单的用户签到功能的详细内容,更多关于Java实现用户签到功能的资料请关注毛票票其它相关文章!