需求:前台展示图片,之前系统是从服务器磁盘路径中读取,当图片数量多的时候,由于读写操作耗时,就会导致页面出现卡的感觉。
解决方案:使用缓存技术,在第一次浏览过图片之后,将图片的byte[]流缓存到MAP中,下次在访问的时候直接缓存获取就可以。
 
样例代码:
jsp调用方式如下:
<img id="showImg" src="loadImage.action?picName=${pList }" width="110px" height="75px" />
 
后台类的写法:
	public void loadImage() throws Exception {
		ActionContext context = ActionContext.getContext();
		HttpServletResponse imgResponse = (HttpServletResponse) context
				.get(ServletActionContext.HTTP_RESPONSE);
		HttpServletRequest imgRequest = (HttpServletRequest) context
				.get(ServletActionContext.HTTP_REQUEST);
		String picName = imgRequest.getParameter("picName");
		String[] picNames = picName.split("/");
		String url = Constant.HDFS_PREFIX + Constant.HDFS_AD_PREFIX
				+ picNames[picNames.length - 1];
		// 根据URL获取图片流
		byte[] picStream = ImgUtil.AD_PIC_MAP.get(url);
		InputStream in = new ByteArrayInputStream(picStream);
		BufferedOutputStream bout = new BufferedOutputStream(
				imgResponse.getOutputStream());
		try {
			byte b[] = new byte[1024];
			int len = in.read(b);
			while (len > 0) {
				bout.write(b, 0, len);
				len = in.read(b);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			bout.close();
			in.close();
		}
	}
 
以上是我工程的代码,可参照改成自己的项目。
参考网址:http://www.blogjava.net/focusJ/archive/2011/04/30/367243.html
 
 
 
 
                   
                   
                   
                   
                            
 
                             本文介绍了一种通过缓存技术优化图片加载速度的方法,适用于图片数量庞大的场景。通过将图片的byte[]流缓存到MAP中,减少服务器磁盘的读写操作,从而提高页面加载效率。
本文介绍了一种通过缓存技术优化图片加载速度的方法,适用于图片数量庞大的场景。通过将图片的byte[]流缓存到MAP中,减少服务器磁盘的读写操作,从而提高页面加载效率。
           
       
           
                 
                 
                 
                 
                 
                
               
                 
                 
                 
                 
                
               
                 
                 扫一扫
扫一扫
                     
              
             
                   3024
					3024
					
 被折叠的  条评论
		 为什么被折叠?
被折叠的  条评论
		 为什么被折叠?
		 
		  到【灌水乐园】发言
到【灌水乐园】发言                                
		 
		 
    
   
    
   
             
            


 
            