本文共 2480 字,大约阅读时间需要 8 分钟。
@Controller
@RequestMapping("/goods")public classGoodsController {
@AutowiredprivateMiaoshaUserService miaoshaUserService;
@AutowiredprivateGoodsService goodsService;
@AutowiredprivateRedisService redisService;
@AutowiredprivateThymeleafViewResolver thymeleafViewResolver;
@Autowired
ApplicationContext applicationContext;
@RequestMapping(value= "/to_list",produces = "text/html")
@ResponseBodypublicString list(Model model, MiaoshaUser user, HttpServletRequest request,HttpServletResponse response){
model.addAttribute("user",user);
String html= redisService.get(GoodsKey.getGoodsList, "", String.class);if(!StringUtils.isEmpty(html)){
System.out.println("从缓存中取");returnhtml;
}
List goodsList =goodsService.listGoodsVo();
model.addAttribute("goodsList",goodsList);
SpringWebContext ctx= newSpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext);//手动渲染
html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);if(!StringUtils.isEmpty(html)){
redisService.set(GoodsKey.getGoodsList,"",html);
}
System.out.println("从数据库中取");returnhtml;
}
@RequestMapping(value= "/to_detail/{goodsId}", produces = "text/html")
@ResponseBodypublicString detail(HttpServletRequest request,HttpServletResponse response,Model model, MiaoshaUser user,
@PathVariable("goodsId") longgoodsId){
model.addAttribute("user",user);
String html=redisService.get(GoodsKey.getGoodsDetail,""+goodsId,String.class);if(!StringUtils.isEmpty(html)){
System.out.println("从缓存中取");returnhtml;
}
GoodsVo goods=goodsService.getGoodsVoByGoodsId(goodsId);
model.addAttribute("goods", goods);//得到秒杀的开始时间、结束时间、以及当前时间
long startAt =goods.getStartDate().getTime();long endAt =goods.getEndDate().getTime();long now =System.currentTimeMillis();//设置剩余时间
int remainSeconds=0;//设置秒杀状态
int miaoshaStatus=0;//判断
if(now
miaoshaStatus=0;
remainSeconds= (int) ((startAt-now)/1000);
}else if(now>endAt){//秒杀已经结束
miaoshaStatus=2;
remainSeconds=-1;
}else{//秒杀正在进行
miaoshaStatus=1;
remainSeconds=0;
}
model.addAttribute("miaoshaStatus",miaoshaStatus);
model.addAttribute("remainSeconds",remainSeconds);
SpringWebContext ctx= newSpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext);//手动渲染
html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);if(!StringUtils.isEmpty(html)){
redisService.set(GoodsKey.getGoodsDetail,""+goodsId,html);
}
System.out.println("从数据库中取");returnhtml;
}
}
转载地址:http://ferio.baihongyu.com/