3.2. 静态化的实现方式

未匹配的标注

优化思路
系统特征:高并发 大流量
优化方向:提高网站性能,保护数据库
具体措施:静态化 分布式 消息队列

为啥要搞静态化就不废话了,
就跟php框架tp里面的缓存文件一样,这里你得有视图文件作为模板然后再将模板文件搞成静态的缓存文件 道理就这么简单;
golang里面如何实现页面静态化?直接上代码:

//一下代码都是关于页面静态化的操作
var (
   //生成的html保存目录
  htmlOutPath = "./fronted/web/htmlProductShow/"
  //静态文件模板目录
  templatePath = "./fronted/web/views/template/"
)

//生成静态文件的控制器
//访问的时候不要忘记了添加上 ?productID=7func (p *ProductController) GetGenerateHtml(){
   //接收参数并处理
  productString := p.Ctx.URLParam("productID")
   productID, err := strconv.Atoi(productString)
   if err != nil {
      p.Ctx.Application().Logger().Debug(err)
   }
   //1.获取模板
  contentsTmp,err := template.ParseFiles(filepath.Join(templatePath+"/product.html"))
   if err != nil {
      p.Ctx.Application().Logger().Debug(err)
   }
   //2.获取html生成路径
  fileName := filepath.Join(htmlOutPath+"/htmlProduct.html")
   //3.获取模板渲染数据
  product, err := p.ProductService.GetProductById(int64(productID))
   if err != nil {
      p.Ctx.Application().Logger().Debug(err)
   }
   //4.生成静态文件
  generateStaticHtml(p.Ctx,contentsTmp,fileName,product)
}

//上下文 *template.Template表示生成模板如果是text则会以文本形式输出   模板静态文件生成的路径  要渲染到模板里面去的数据
func generateStaticHtml(ctx iris.Context,template *template.Template,fileName string,product *datamodels.Product) {
   //1.判断静态文件是否存在
  if exist(fileName) {
      err := os.Remove(fileName)
      if err != nil {
         ctx.Application().Logger().Error(err)
      }
   }
   //2.生成静态文件
  //os.openFile()第一个参数是文件路径 第二个参数是文件的打开方式 第三个参数是控制文件模式   更多的文件读写操作参考https://blog.csdn.net/qq_30895047/article/details/106827889博文
  file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, os.ModePerm)
   if err != nil {
      ctx.Application().Logger().Error(err)
   }
   defer file.Close()
   template.Execute(file, &product)
}

//生成文件之前先要判断文件是否存在
func exist(fileName string) bool {
   //获取文件的各种信息
  _, err := os.Stat(fileName)
   return err == nil || os.IsExist(err)
}

周全点,将目录结构也提供给大家:

服务端优化思路以及静态化的实现方式
除此之外还需要在main里面配置/html 那么就可以直接通过域名/html/htmlproduct.html访问我们的静态化界面了:
服务端优化思路以及静态化的实现方式

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~