freemarker+minio实现页面静态化

什么是页面静态化?

将原本动态生成的网页内容通过某种形式转化为html并存储在服务器上,当用户请求这些页面时就不需要执行逻辑运算和数据库读

优点:

  • 性能:提高页面加载速度和响应速度,还可以减轻数据库、服务器的负担
  • 安全性:不涉及服务器端脚本执行,减少因代码漏洞而被攻击的风险

 

实现步骤:通过freemarker生成固定模板->将模板写入minIO->读取

1.freemarker生成固定模板

    public File generateCourseHtml(Long courseId) {
        //配置freemarker
        Configuration configuration = new Configuration(Configuration.getVersion());
        File htmlFile=null;
        try {
            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");
            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");
            //准备数据。这里model使用map
            CoursePreviewDto coursePreviewInfo = getCoursePreviewInfo(courseId);
            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            //静态化
            //参数1:模板,参数2:数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);

            htmlFile = File.createTempFile("course", ".html");
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(htmlFile==null){
            throw new XueChengPlusException("生成静态文件失败");
        }
        return htmlFile;
    }

2.minIO写入:这里规定是两个功能属于不同模块,使用feign进行调用

feign接口

/**
 * 远程调用媒资的接口
 */
@FeignClient(value = "media-api",configuration = MultipartSupportConfig.class,fallbackFactory = MediaServiceClientFallback.class)
public interface MediaServiceClient {
    @RequestMapping(value = "/media/upload/coursefile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String uploadCoursefile(@RequestPart("filedata") MultipartFile filedata,
                                                @RequestParam(value="objectName",required = false)String objectName
    ) throws IOException;
}

minIO上传controller

    @ApiOperation("上传文件接口")
    @RequestMapping(value = "/upload/coursefile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public UploadFileResultDto uploadCoursefile(@RequestPart("filedata")MultipartFile filedata,
                                                @RequestParam(value="objectName",required = false)String objectName
    ) throws IOException {
        File tempFile=File.createTempFile("minio", ".temp");
        filedata.transferTo(tempFile);
        String absolutePath = tempFile.getAbsolutePath();
        return mediaFileService.upload(filedata,absolutePath,objectName);
    }

minIO上传实现service。注:下文的filename即absolutePath;object需要指定具体路径,例如我使用了上文的objectName+“//”+filedata.getOriginalFilename()

    public boolean uploadToMinio(String bucket, String filename, String object, String mimeType) {
        try {
            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(bucket)
                            .filename(filename)
                            .object(object)
                            .contentType(mimeType)
                            .build()
            );
            log.info("文件上传成功:{}", object);
            return true;
        } catch (Exception e) {
            log.error("上传文件到minio失败:{}", e.getMessage());
        }
        return false;
    }

 

posted @ 2024-07-16 22:27  天启A  阅读(115)  评论(0)    收藏  举报