我们有一个为图像服务的应用程序,为了加快响应时间,我们直接将 BufferedImage 缓存在内存中。
BufferedImage
class Provider { @Override public IData render(String... layers,String coordinate) { int rwidth = 256 , rheight = 256 ; ArrayList<BufferedImage> result = new ArrayList<BufferedImage>(); for (String layer : layers) { String lkey = layer + "-" + coordinate; BufferedImage imageData = cacher.get(lkey); if (imageData == null) { try { imageData = generateImage(layer, coordinate,rwidth, rheight, bbox); cacher.put(lkey, imageData); } catch (IOException e) { e.printStackTrace(); continue; if (imageData != null) { result.add(imageData); return new Data(rheight, rheight, width, result); private BufferedImage generateImage(String layer, String coordinate,int rwidth, int rheight) throws IOException { BufferedImage image = new BufferedImage(rwidth, rheight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setColor(Color.RED); g.drawString(layer+"-"+coordinate, new Random().nextInt(rwidth), new Random().nextInt(rheight)); g.dispose(); return image; class Data implements IData { public Data(int imageWidth, int imageHeight, int originalWidth, ArrayList<BufferedImage> images) { this.imageResult = new BufferedImage(this.imageWidth, this.imageHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = imageResult.createGraphics(); for (BufferedImage imgData : images) { g.drawImage(imgData, 0, 0, null); imgData = null; imageResult.flush(); g.dispose(); images.clear(); @Override public void save(OutputStream out, String format) throws IOException { ImageIO.write(this.imageResult, format, out); out.flush(); this.imageResult = null; }
用法:
class ImageServlet extends HttpServlet { void doGet(req,res){ IData data= provider.render(req.getParameter("layers").split(",")); OutputStream out=res.getOutputStream(); data.save(out,"png") out.flush();