Spring MVC中的内存高效XML修改

时间:2018-04-06 13:28:03

标签: java xml spring xslt streaming

下面的方法将返回一个XML响应,其中一些属性值是pre-& amp;固定岗位。 在尝试STAX之后,我现在尝试使用TRAX来转换XML。 有什么办法可以减少内存负载吗?

import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@RestController
public class MyController {

@RequestMapping
public void get(HttpServletResponse response) throws IOException, TransformerException {

    LOGGER.info("Total {} mb", Runtime.getRuntime().totalMemory()/1000000);
    LOGGER.info("Free {} mb", Runtime.getRuntime().freeMemory()/1000000);
    LOGGER.info("Used {} mb", (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1000000);

    StreamSource xml = new StreamSource(new URL("http://remote.domain/big.xml").openStream());
    TransformerFactory factory = TransformerFactory.newInstance();
    Source xsl = new StreamSource(new ClassPathResource("transform.xsl").getInputStream());
    Result result = new StreamResult(response.getOutputStream());
    Transformer transformer = factory.newTransformer(xsl);
    transformer.setParameter("prefix", "BEFORE");
    transformer.setParameter("postfix", "AFTER");
    response.setContentType("application/xml");
    response.setHeader("Content-Disposition", "attachment; filename=updated.xml" );
    transformer.transform(xml, result);
    response.flushBuffer();

    LOGGER.info("Total {} mb", Runtime.getRuntime().totalMemory()/1000000);
    LOGGER.info("Free {} mb", Runtime.getRuntime().freeMemory()/1000000);
    LOGGER.info("Used {} mb", (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1000000);

}
}

请注意xsl通常会加载一次。为了便于阅读,我在这个方法中添加了所有内容。

编辑如果我多次调用该方法,我会得到一个java.lang.OutOfMemoryError: Java heap space。所以,我认为它根本不是流媒体

0 个答案:

没有答案