秒杀服务中的商品详情页

131 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第26天,点击查看活动详情

每日英语:

The good life is one inspired by love and guided by knowledge.

翻译:美好人生是启之以爱、导之以知的人生。 ——伯特兰·罗素

商品详情页

秒杀商品详情页访问频率一定非常高,我们将详情页做成生成静态页或者从缓存加载用来提升访问效率。我们这里选择将详情页生成静态页。

静态页生成实现

我们直接修改之前的mall-page-web工程,在里面创建Controller、Service。静态页生成保存路径存在到G:/pages/seckillitems/

1)bootstrap.yml配置

在bootstrap.yml中添加如下路径配置:

#秒杀静态页
itemPath: G:/pages/seckillitems/

2)Service

接口:创建com.xz.mall.page.service.SeckillPageService,并添加生成秒杀静态页方法:

public interface SeckillPageService {
​
    /***
     * 生成静态页
     */
    void html(String id) throws Exception;
}

实现类:创建com.xz.mall.page.service.impl.SeckillPageServiceImpl并实现生成静态页方法:

@Service
public class SeckillPageServiceImpl implements SeckillPageService {
​
    @Autowired
    private TemplateEngine templateEngine;
​
    @Value("${itemPath}")
    private String itemPath;
​
    @Autowired
    private SeckillGoodsFeign seckillGoodsFeign;
​
    /****
     * 生成静态页
     */
    @Override
    public void html(String id) throws Exception {
        //加载数据
        Map<String,Object> dataMap = dataLoad(id);
​
        //创建Thymeleaf容器对象
        Context context = new Context();
        //设置页面数据模型
        context.setVariables(dataMap);
        //文件名字  id.html
        File dest = new File(itemPath, id + ".html");
        PrintWriter writer = new PrintWriter(dest, "UTF-8");
        //生成页面
        templateEngine.process("item", context, writer);
    }
​
    /***
     * 加载数据
     * @param id
     * @return
     */
    private Map<String,Object> dataLoad(String id) {
        RespResult<SeckillGoods> goodsResp = seckillGoodsFeign.one(id);
        //将商品信息存入到Map中
        if(goodsResp.getData()!=null){
            Map<String,Object> dataMap = new HashMap<String,Object>();
            dataMap.put("item",goodsResp.getData());
            return dataMap;
        }
        return null;
    }
}

3)Controller

创建com.xz.mall.page.controller.SeckillPageController实现生成静态页方法调用,代码如下:

@RestController
@RequestMapping(value = "/page")
public class SeckillPageController {
​
    @Autowired
    private SeckillPageService seckillPageService;
​
    /***
     * 秒杀详情页生成
     * @param id
     * @return
     */
    @GetMapping(value = "/seckill/goods/{id}")
    public RespResult page(@PathVariable(value = "id")String id) throws Exception {
        //生成静态页
        seckillPageService.html(id);
        return RespResult.ok();
    }
}

Feign接口实现

其他工程一旦发现数据发生变更,会调用上面方法生成静态页,因此我们需要编写feign接口。

mall-page-api中创建com.xz.mall.page.feign.SeckillPageFeign

@FeignClient(value = "mall-web-page")
public interface SeckillPageFeign {
​
    /***
     * 秒杀详情页生成
     * @param id
     * @return
     */
    @GetMapping(value = "/page/seckill/goods/{id}")
    RespResult page(@PathVariable(value = "id")String id) throws Exception;
}

总结

本篇主要介绍了一下秒杀服务中商品静态页的生成实现。