远程请求接口
	SpringMVC提供 RestTemplate请求http接口,RestTemplate的底层可以使用第三方的http客户端工具实现http 的请求,常用的http客户端工具有Apache HttpClient、OkHttpClient等,本项目使用OkHttpClient完成http请求,原因也是因为它的性能比较出众。
使用步骤:
1.添加依赖
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
</dependency>
2.在启动类中,配置RestTemplate对象
@Bean
public RestTemplate restTemplate(){
	return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
3.RestTemplate API
ResponseEntity<Map> entityMap = restTemplate.getForEntity(\"api接口的请求url\",Map.class);
Map responseMap = entityMap.getBody();
GridFs
	GridFs是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFs可以快速集成
开发。
工作原理:
	在GridFs存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFs使用两个集合
(collection)存储文件,一个集合是chunks, 用于存储文件的二进制数据;一个集合是files,用于存储文件的元数
据信息(文件名称、块大小、上传时间等信息)。
从GridFS中读取文件要对文件的各各块进行组装、合并。
详细链接:
	https://docs.mongodb.com/manual/core/gridfs/

GridFsTemplate API: (GridFsTemplate在SpringBoot工程下可以直接@Autowired)
/存储文件
//获取输入流,读取需要保存到mongoDB中的文件
InputStream is = new FileInputStream(new File(\"g:/a.txt\"));		//如果文件大于256KB,将会自动被拆分
//参数1:字节输入流,参数2:文件名,返回值类型: Id; Id也是mongodb中存储的ID
 Id  Id = gridFsTemplate.store(is,\"测试文件.txt\");	

文件存储成功得到一个文件id
此文件id是fs.files集合中的主键。
可以通过文件id查询fs.chunks表中的记录,得到文件的内容。

//读取文件
GridFSBucket(需要使用@Bean注解注入)
//1.配置一个注解配置类,专门用来注入Bean对象,注入GridFSBucket
@Configuration
public class MongoConfig{
	@Bean
    public GridFSBucket gridFSBucket(MongoClient mongoClient){
		MongoData  data  = mongoClient.getData (data Name);
		GridFSBucket gridFSBucket = GridFSBuckets.create(data );
		return gridFSBucket;
    }
}
//开始读取
public void testDownload(){
	//根据文件ID查询GridFsFile对象
	GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(new Criteria(\"_id\").is(\"文件ID\")));
    //获取GridFS下载流对象
	GridFSDownloadStream gridFSDownloadStream =
gridFSBucket.openDownloadStream(gridFSFile.get Id());
    //获取GridFS中的资源
   GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
	//获取文件内容
   String content = IOUtils.toString(gridFsResource.getInputStream(), \"utf-8\");
}
//删除文件
gridFsTemplate.delete(new Query(new Criteria(\"_id\").is(\"文件ID\")));

根据页面ID生成html响应到前端
	//service层入口
    public String getPageHtml(String pageId) {
        try {//数据模型
            Map map = new HashMap();
            Map resultMap = getDataModel(pageId);
            if (resultMap == null) {
                ExceptionCast.cast(CommonCode.SERVER_ERROR);
            }
            map.put(\"modelMap\",resultMap);
            //模板字符串
            String templateString = getTemplateString(pageId);
            if(StringUtils.isEmpty(templateString)){
                ExceptionCast.cast(CommonCode.TEMPLATEFILEID_NOT_EXISTS);
            }
            //文本输出
            Configuration configuration = new Configuration(Configuration.getVersion());
            StringTemplateLoader templateLoader = new StringTemplateLoader();
            templateLoader.putTemplate(\"templateString\", templateString);
            configuration.setTemplateLoader(templateLoader);
            Template template = configuration.getTemplate(\"templateString\");
            String templateFileString = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            return templateFileString;
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 根据pageId从collection:cms_page中查询dataUrl,通过dataUrl获取数据模型
     *
     * @param pageId
     * @return
     */
    private Map getDataModel(String pageId) {
        Optional<CmsPage> optional = cmsPageRepository.findById(pageId);
        if (!optional.isPresent()) {
            ExceptionCast.cast(CommonCode.ENTITY_NOT_FIND);
        }
        //说明查询到了
        CmsPage cmsPage = optional.get();
        String dataUrl = cmsPage.getDataUrl();
        if (!StringUtils.isNotEmpty(dataUrl)) {
            //没有dataUrl
            ExceptionCast.cast(CommonCode.URL_NOT_EXISTS);
        }
        //发送Http请求,获取数据来源
        System.out.println(\"dataUrl:\" + dataUrl);
        ResponseEntity<Map> responseEntity = restTemplate.getForEntity(dataUrl, Map.class);
        if (responseEntity != null) {
            Map resultMap = responseEntity.getBody();
            return resultMap;
        }
        return null;
    }

    /**
     * 根据pageId得到cmsPage对象,获得cmsPage对象中的templateId,取cms_template中查询
     *
     * @param pageId
     * @return
     */
    private String getTemplateString(String pageId) {
        try {
            Optional<CmsPage> optional1 = cmsPageRepository.findById(pageId);
            if (!optional1.isPresent()) {
                ExceptionCast.cast(CommonCode.ENTITY_NOT_FIND);
            }
            CmsPage cmsPage = optional1.get();
            String templateId = cmsPage.getTemplateId();
            if (!StringUtils.isNotEmpty(templateId)) {
                ExceptionCast.cast(CommonCode.TEMPLATEID_NOT_EXISTS);
            }
            //根据模板ID查询模板对象
            Optional<CmsTemplate> optional2 = cmsTemplateRepository.findById(templateId);
            if (!optional2.isPresent()) {
                ExceptionCast.cast(CommonCode.ENTITY_NOT_FIND);
            }
            CmsTemplate cmsTemplate = optional2.get();
            String templateFileId = cmsTemplate.getTemplateFileId();
            if (!StringUtils.isNotEmpty(templateFileId)) {
                ExceptionCast.cast(CommonCode.TEMPLATEFILEID_NOT_EXISTS);
            }
            //根据模板文件ID从chunks中获取模板字符串
            //根据文件ID查询GridFsFile对象
            GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(new Criteria(\"_id\").is(templateFileId)));
            //获取GridFS下载流对象
            GridFSDownloadStream gridFSDownloadStream = gridFsBucket.openDownloadStream(gridFSFile.get Id());
            //获取GridFS中的资源
            GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
            //获取文件内容
            String content = IOUtils.toString(gridFsResource.getInputStream(), \"utf-8\");
            return content;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
收藏 打印