Java的新專案學成線上筆記-day4(四)
3.3.2.2 模板測試
在freemarker測試工程編寫一個方法測試輪播圖模板,程式碼如下:
@Autowired RestTemplate restTemplate; @RequestMapping("/banner") public String index_banner(Map<String, Object> map){ String dataUrl = "http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f"; ResponseEntity<Map> forEntity = restTemplate.getForEntity(dataUrl, Map.class); Map body = forEntity.getBody(); map.putAll(body); return "index_banner"; }
請求:http://localhost:8088/freemarker/banner
3.3.3 GridFS研究 3.3.3.1 GridFS介紹
GridFS是MongoDB提供的用於持久化儲存檔案的模組,CMS使用MongoDB儲存資料,使用GridFS可以快速整合 開發。
它的工作原理是:
在GridFS儲存檔案是將檔案分塊儲存,檔案會按照256KB的大小分割成多個塊進行儲存,GridFS使用兩個集合 (collection)儲存檔案,一個集合是chunks, 用於儲存檔案的二進位制資料;一個集合是files,用於儲存檔案的元數 據信息(檔名稱、塊大小、上傳時間等資訊)。
從GridFS中讀取檔案要對檔案的各各塊進行組裝、合併。
詳細參考:
1、存檔案 使用GridFsTemplate儲存檔案測試程式碼: 向測試程式注入GridFsTemplate。
@Test public void testGridFs() throws FileNotFoundException { //要儲存的檔案 File file = new File("d:/index_banner.html"); //定義輸入流 FileInputStream inputStram = new FileInputStream(file); //向GridFS儲存檔案 ObjectId objectId = = gridFsTemplate.store(inputStram, "輪播圖測試檔案01", ""); //得到檔案ID String fileId = objectId.toString(); System.out.println(file); }
儲存原理說明:
檔案儲存成功得到一個檔案id 此檔案id是fs.files集合中的主鍵。
可以通過檔案id查詢fs.chunks表中的記錄,得到檔案的內容。
2、讀取檔案 1)在config包中定義Mongodb的配置類,如下: GridFSBucket用於開啟下載流物件
@Configuration public class MongoConfig {
@Value("${spring.data.mongodb.database}")
String db;
@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient){
MongoDatabase database = mongoClient.getDatabase(db);
GridFSBucket bucket = GridFSBuckets.create(database);
return bucket;
}
}
2)測試程式碼如下
@SpringBootTest
@RunWith(SpringRunner.class)
public class GridFsTest {
@Autowired
GridFsTemplate gridFsTemplate;
@Autowired
GridFSBucket gridFSBucket;
@Test
public void queryFile() throws IOException {
String fileId = "5b9c54e264c614237c271a99";
//根據id查詢檔案
GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
//開啟下載流物件
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//建立gridFsResource,用於獲取流物件
GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
//獲取流中的資料
String s = IOUtils.toString(gridFsResource.getInputStream(), "UTF‐8");
System.out.println(s);
}
...
3、刪除檔案
//刪除檔案
@Test public void testDelFile() throws IOException {
//根據檔案id刪除fs.files和fs.chunks中的記錄
gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5b32480ed3a022164c4d2f92")));
}
3.3.4 模板儲存
根據模板管理的流程,最終將模板資訊儲存到MongoDB的cms_template中,將模板檔案儲存到GridFS中。 模板管理功能在課堂中不再講解,教學中手動向cms_template及GridFS中儲存模板,方法如下:
1、新增模板
1)使用GridFS測試程式碼儲存模板檔案到GridFS,並得到檔案id.
2)向cms_template新增記錄。
2、刪除模板
1)使用GridFS測試程式碼根據檔案id刪除模板檔案。
2)根據模板id刪除cms_template中的記錄。
3、修改模板資訊 使用Studio 3T修改cms_template中的記錄。
4、修改模板檔案
1)通過Studio 3T修改模板檔案(此方法限檔案小於256K)
可以通過Studio 3T修改模板檔案,先找到模板檔案,再匯入進去: