天天看點

Spring+Freemarker+阿裡雲OSS實作網頁靜态化與檔案共享存儲

        Freemarker是一款非常流行的模闆引擎架構,至于基本用法,網上度娘裡面有一大堆,我這裡就不在叙述了。本文主要介紹的是采用阿裡雲OSS做未檔案伺服器,在叢集的模式下面,怎麼實作靜态頁面的生成與共享存儲。

        首先我們知道OSS提供多種檔案上傳方式:

        第一種:檔案

        第二種:檔案流

        第三種:byte數組。

       我開始的處理方式是:

       1、擷取模闆檔案.ftl檔案

       2、使用模闆檔案,采用freemarker生成靜态頁面到本地伺服器上的臨時檔案。

       3、讀取生成的檔案,形成檔案流,調用OSS的API上傳到阿裡雲伺服器上。

       4、删除本地臨時檔案。

      這樣的處理方式,流程上是沒什麼問題,但是會有以下幾個弊端:

       1、增加IO操作

       2、流程複雜化,增加處理時長。

       那麼現在我們簡化流程如下:

       1、擷取模闆檔案。

       2、采用字元流StringWriter對模闆進行處理。

       3、通過字元流擷取檔案内容的字元串。

       4、調用OSS的API,将字元串轉換成位元組數組Put到OSS的伺服器上去。

       從過程中我們可以很清晰的看出來,我們把中間的檔案轉換,删除等操作全部去除,進而節省運作成本和IO操作。

最後奉獻生成工具類:

public static String createHtml(String modelName, String tempOutPath, Map<String, Object> dataModel,
			String reportType,String rootPath,String uploadPath) {
		// TODO Auto-generated method stub
		StringWriter out = new StringWriter();
		try {
			 // 第一步:建立一個Configuration對象,直接new一個對象。構造方法的參數就是freemarker對于的版本号。  
	         Configuration configuration = new Configuration(Configuration.getVersion());  
	         // 第二步:設定模闆檔案所在的路徑。  
	         configuration.setDirectoryForTemplateLoading(new File(rootPath+File.separator+"WEB-INF"+File.separator+"ftl"));  
	         // 第三步:設定模闆檔案使用的字元集。一般就是utf-8.  
	         configuration.setDefaultEncoding("utf-8");  
	         // 第四步:加載一個模闆,建立一個模闆對象。  
	         Template template = configuration.getTemplate(modelName);  
	         // 第六步:建立一個Writer對象,一般建立一FileWriter對象,指定生成的檔案名。  
//	         File temFile = new File(uploadPath);
//	         if(!temFile.exists()){
//	        	 temFile.mkdirs();
//	         }
//	         File file = new File(uploadPath+tempOutPath+".html");
//	         if (file.exists()) {
//				file.mkdirs();
//			}
//	         Writer out = new FileWriter(file);  
	         // 第七步:調用模闆對象的process方法輸出檔案。  
	         template.process(dataModel, out);  
	         // 第八步:關閉流。  
//	         out.close();  
	         PubAliyunUtil.putObjectToResouceALL(out.toString().getBytes("UTF-8"), "report/"+reportType+"/"+tempOutPath+".html");
	         //删除檔案
//	         if(file.exists()){
//	        	 file.delete();
//	         }
	         String url = URL+ "report/"+reportType+"/"+tempOutPath+".html";
	         QRCodeUtil.encode(url, rootPath+File.separator+"images"+File.separator+"erweima_logo.jpg", true, 2, "report/"+reportType+"/"+tempOutPath+".jpg");
	         return URL+ "report/"+reportType+"/"+tempOutPath+".jpg";
		} catch (Exception e) {
			e.printStackTrace();
		}  finally{
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}