前言
大家都知道淘寶、天貓、京東以及聚美之類的電商網站,她們的商品頁會存在多套模板,各套模板的元數據是一樣的,只是展示方式不一樣。特別是對于店主而言商品詳情頁個性化需求非常多,就商品單頁各個維度信息來說,數據來源也是非常多的。這時候,如果我們再實時的去查詢各個數據源組織數據,對于數據庫來說開銷是巨大的,秒殺更是如此。
靜態化
在這里我們就做一個簡單商品詳情頁靜態頁生成,大家工作中根據實際情況做調整優化。后面如果大家對商品詳情頁架構感興趣,可以去了解下《億級流量網站架構核心技術》書中的如何構建需求響應式億級商品詳情頁,畢竟前人栽樹后人乘涼,里面還是有很多大家可以借鑒的地方。
我們選用freemarker做模板,pom.xml引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
application.properties配置相關參數:
#freemarker(用于商品靜態頁生成簡化版)
spring.freemarker.template-loader-path=classpath:/static/template/
spring.freemarker.suffix=.flt
spring.freemarker.enabled=true
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.allow-request-override=false
spring.freemarker.check-template-location=true
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#商品靜態頁
spring.freemarker.html.path = D://file//
goods.flt定義商品單頁模板:
# 模板太大了,這里不做展示,請自行參考源碼
static/template/goods.flt
ICreateHtmlService靜態化接口:
publicinterfaceICreateHtmlService{
Result createAllHtml();
}
CreateHtmlServiceImpl靜態化實現:
@Service
publicclassCreateHtmlServiceImplimplementsICreateHtmlService{
privatestaticint corePoolSize = Runtime.getRuntime().availableProcessors();
privatestatic ThreadPoolExecutor executor =
new ThreadPoolExecutor(corePoolSize, corePoolSize+1, 10l, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(1000));
@Autowired
public Configuration configuration;
@Autowired
private SeckillRepository seckillRepository;
@Value("${spring.freemarker.html.path}")
private String path;
@Override
public Result createAllHtml(){
List<Seckill> list = seckillRepository.findAll();
final List<Future<String>> resultList = new ArrayList<Future<String>>();
for(Seckill seckill:list){
resultList.add(executor.submit(new createhtml(seckill)));
}
for (Future<String> fs : resultList) {
try {
System.out.println(fs.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
return Result.ok();
}
classcreatehtmlimplementsCallable<String> {
Seckill seckill;
publiccreatehtml(Seckill seckill){
this.seckill = seckill;
}
@Overridepublic String call()throws Exception {
Template template = configuration.getTemplate("goods.flt");
File file= new File(path+seckill.getSeckillId()+".html");
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
template.process(seckill, writer);
return"success";
}
}
}
最后通過swagger-ui頁面執行以下生成商品頁操作,不出意外目錄下會生成四個商品頁面,打開如下圖所示:
思考




