使用 JRLoader.loadObject 加载“.jasper”报告模板文件很浪费内存。我想知道加载的JasperReport是否可以缓存复用? 相关代码如下:
public JasperReport getJasperReport(String jasperTemplateName){
ClassPathResource resource = new ClassPathResource(ReportConstant.JASPER_PATH + jasperTemplateName + ".jasper");
try (InputStream jasperStream = resource.getInputStream()) {
return (JasperReport) JRLoader.loadObject(jasperStream);
} catch (JRException | IOException e) {
log.error(e.toString(),e);
}
}
private static final Map<String, JasperReport> JASPER_REPORT_MAP = new HashMap<>(16);
@PostConstruct
public void init() {
JASPER_REPORT_MAP.put(REPORT_NAME_SSCP0001, getJasperReport(REPORT_NAME_0001));
JASPER_REPORT_MAP.put(REPORT_NAME_SSCP0003, getJasperReport(REPORT_NAME_0002));
}
public <T> JasperPrint getJasperPrint(String jasperTemplateName, Map<String,Object> parameters,
List<T> listData){
try {
JRGzipVirtualizer virtualizer = new JRGzipVirtualizer(2);
parameters.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
return JasperFillManager.fillReport(JASPER_REPORT_MAP.get(jasperTemplateName), parameters, new JRBeanCollectionDataSource(listData));
} catch (JRException e) {
log.error(e.toString(), e);
throw new BusinessException(PublicErrorCode.SYSTEM_ERROR.getCode(), "jasper Failed to populate jasper data");
}
}
在JasperReport缓存的HashMap中,每次生成报告时,都会从map中获取JasperReport,然后填充数据生成报告。可以这样使用吗? 每次使用时从文件中加载 JasperReport (JRLoader.loadObject(InputStream)) 会导致内存使用量快速增加。