背景:需要查询某个表然后生成sitemap.xml文件,部署服务器的时候发觉无法生成,检查发现是由于读取数据库的时候一下子查询的结果集太大,大概有50w条,导致响应很久都没有结果,需要进行分页查询,改造的思路如下:
DepartmentKeyword vo = new DepartmentKeyword();
vo.setStatus(10);
int total=bxkcDepartmentKeywordService.countKeywordList(vo);
int pageNo = total/pageSize+1;//总页数
首先去查询总记录数,执行sql相当于:select count(*) from xxxx;pageNo表示分页的总数,pageSize表示每次查询的条数,+1表示最后一页
for (int i = 1; i <= pageNo; i++) {
StringBuffer buffer = new StringBuffer();
list = bxkcDepartmentKeywordService.getKeywordList(vo,i,pageSize);
File file= createFile(i, relativelyPath,indexPath, fos, pw,buffer);
for (int j = 0; j < list.size(); j++) {
buffer.append("<url>\r\n");
buffer.append("<loc>http://www.xxx.com/public/"+list.get(j).getPinyin()+"</loc>\r\n");
buffer.append("<lastmod>"+currentTime+"</lastmod>\r\n");
buffer.append("<changefreq>daily</changefreq>\r\n");
buffer.append("<priority>0.7</priority>\r\n");
buffer.append("</url>\r\n");
}
buffer.append("</urlset>\r\n");
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(buffer.toString().toCharArray());
pw.flush();
pw.close();
}
生成文件方法
public File createFile(Integer count,String relativelyPath,String indexPath,FileOutputStream fos,PrintWriter pw,StringBuffer buff) throws Exception {
File file=new File(indexPath);
if(!file.exists()){
file.mkdir();//创建文件夹
}
String path= indexPath + "/public"+count+".xml";
File fileName = new File(path);
if (!fileName.exists()) {
fileName.createNewFile();
}
buff.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
buff.append("<urlset>\r\n");
return fileName;
}
也就是每查找一页生成一个xml文件,效果如下