秒杀优化

一、页面缓存、对象缓存
在一个页面中,我们必须尽可能减少对数据库的访问。在并不影响用户体验的前提下,对于静态或变化不大的页面,可以使用页面缓存来减少对数据库的访问。
我们在秒杀页面中,如果访问的数据库次数越多,耗时也就越长,使用时间越长,性能就差,用户体验会降低。因此减少数据库访问,降低逻辑复杂度,把一些频繁用到但变化不大的数据缓存起来就提高了性能。

@RequestMapping("to_list")
public String toList(Model model,MiaoshaUser user){
    if(user == null)
        return "login";
    model.addAttribute("user",user);
    List<GoodsVo> goodsVoList = goodsService.getGoodsVoList();
    model.addAttribute("goodsList",goodsVoList);
    return "goods_list";
}

对象缓存其实和页面缓存是相同的原理。将频繁用到、但变化不大的对象缓存起来,减少对数据库的访问,提高性能。
二、商品详情静态化、秒杀静态化、订单详情静态化
静态化就是把动态生成的页面,转变为静态的页面保存。如果以后接收到用户的请求,直接访问静态页面,不需要经过服务的渲染。
首先需要创建静态Service。

@Service
public class GoodsHtmlService {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private TemplateEngine templateEngine;
    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsHtmlService.class);
    /**
     * 创建html页面
     *
     * @param spuId
     * @throws Exception
     */
    public void createHtml(Long spuId) {
        PrintWriter writer = null;
        try {
            // 获取页面数据
            Map<String, Object> spuMap = this.goodsService.loadModel(spuId);
            // 创建thymeleaf上下文对象
            Context context = new Context();
            // 把数据放入上下文对象
            context.setVariables(spuMap);
            // 创建输出流
            File file = new File("C:\\project\\nginx-1.14.0\\html\\item\\" + spuId + ".html");
            writer = new PrintWriter(file);
            // 执行页面静态化方法
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            LOGGER.error("页面静态化出错:{},"+ e, spuId);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(()->createHtml(spuId));
        /*ThreadUtils.execute(new Runnable() {
            @Override
            public void run() {
                createHtml(spuId);
            }
        });*/
    }
}

然后在GoodsController中生成我们的静态页面。

@GetMapping("{id}.html")
public String toItemPage(@PathVariable("id")Long id, Model model){
    // 加载所需的数据
    Map<String, Object> map = this.goodsService.loadModel(id);
    // 把数据放入数据模型
    model.addAllAttributes(map);
    // 页面静态化
    this.goodsHtmlService.asyncExcute(id);
    return "item";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值