controller层:
@Controller
@RequestMapping("pages")
public class GoodsPageController {
@Autowired
private GoodsPageService goodsPageService;
@Autowired
private FileService fileService;
@GetMapping("{spuid}.html")
public String toPage(Model model, @PathVariable(value = "spuid")Long spuid) throws Exception {
Map<String,Object> map = goodsPageService.getData(spuid);
model.addAllAttributes(map);
//页面静态化
fileService.asyncExecute(spuid);
return "item";
}
}
service层:
@Slf4j
@Service
public class FileServiceImpl implements FileService {
@Autowired
private GoodsPageService goodsPageService;
@Autowired
private TemplateEngine templateEngine;
@Value("${ddong.thymeleaf.destPath}")
private String destPath;
@Override
public void createHtml(Long spuid) throws Exception{
// 创建上下文,
Context context = new Context();
// 把数据加入上下文
context.setVariables(this.goodsPageService.getData(spuid));
if (!new File(destPath).exists()){
new File(destPath).mkdirs();
}
// 创建输出流,关联到一个临时文件
File temp = new File(destPath+"/"+spuid + ".html");
try (PrintWriter writer = new PrintWriter(temp, "UTF-8")) {
// 利用thymeleaf模板引擎生成 静态页面
templateEngine.process("item", context, writer);
} catch (IOException e) {
log.info("页面静态化出错:{}"+e,spuid);
}
}
/**
* 新建线程处理页面静态化
* @param spuid
*/
@Override
public void asyncExecute(Long spuid) {
ThreadUtils.execute(() -> {
try {
createHtml(spuid);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
工具类:
public class ThreadUtils {
private static final ExecutorService es = Executors.newFixedThreadPool(10);
public static void execute(Runnable runnable){
es.submit(runnable);
}
}
nginx配置:
server {
listen 80;
server_name ddong.com;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location /pages {
# 先找本地
root html;
if (!-f $request_filename) { #请求的文件不存在,就反向代理
proxy_pass http://127.0.0.1:8084;
break;
}
}
}