缓存整个页面到redis,到磁盘

在项目中可以缓存整个页面来提高响应速度,如将首页存到缓存中,需要新建类继承HttpServletResponseWrapper类来实现对响应的静态页面的获取
还需要配置过滤器来拦截页面响应,在拦截器中过滤要拦截的页面,如果该页面存在于缓存中就从缓存中取,如果没有就将页面从后台获取,并存到缓存中
创建的MyResponseWrapper类

import java.io.CharArrayWriter;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class MyResponseWrapper  extends HttpServletResponseWrapper{
    private PrintWriter cachedWriter;
    private CharArrayWriter bufferedWriter;
	public MyResponseWrapper(HttpServletResponse response) {
		super(response);
		 //保存返回结果
		bufferedWriter = new CharArrayWriter();
        // 通过PrintWriter写入到bufferedWriter中
        cachedWriter = new PrintWriter(bufferedWriter);
	}
	 @Override
	    public PrintWriter getWriter() {
	        return cachedWriter;
	    }
	     // 获取原始的HTML页面内容。 
	    public String getResult() {
	        return bufferedWriter.toString();
	    }	
}

缓存到redis

缓存到redis使用Spring提供的工具类
编写过滤器类


public class CacheFilter2 implements Filter {
	  private static ApplicationContext ctx;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub		
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		 HttpServletResponse resp = (HttpServletResponse) response;
	        HttpServletRequest req = (HttpServletRequest) request;     
	        System.out.println(req.getRequestURI()+"-----------------");
	        String url = req.getRequestURI();
	        String substring = url.substring(0, url.lastIndexOf("."));
	        String extName = substring.substring(substring.lastIndexOf("/"));
	       System.out.println(extName);
	        //判断主页
	        if (  req.getRequestURI().equals("/cn.car/login.jsp")==false) {       	
	        	chain.doFilter(request, resp);
	            return;
	        }   
	         String html = getHtmlFromCache();
	          if (null == html) {
	          MyResponseWrapper wrapper = new MyResponseWrapper(resp);
	            chain.doFilter(request, wrapper);
	            // 放入缓存
	            html = wrapper.getResult(); 
	            putIntoCache(html);
	        }
	        // 返回响应
	        resp.setContentType("text/html; charset=utf-8");
	        resp.getWriter().write(html);
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	
   public void setApplicationContext(ApplicationContext applicationContext) {
        this.ctx = applicationContext;
    }
 //取页面
    private String getHtmlFromCache() {
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); 
        StringRedisTemplate redis = (StringRedisTemplate) ac.getBean("redisTemplate");
        return redis.opsForValue().get("home"); 	
    }
 
    //存页面
    private void putIntoCache(String html) {
    	 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); 
        StringRedisTemplate redis = (StringRedisTemplate) ac.getBean("redisTemplate");
        redis.opsForValue().set("home", html, TimeUnit.MINUTES.toSeconds(10));
    }
}

Spring配置文件配置

	<!-- 缓存 -->
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 
        <property name="maxIdle" value="1" /> 
        <property name="maxTotal" value="5" /> 
        <property name="blockWhenExhausted" value="true" /> 
        <property name="maxWaitMillis" value="30000" /> 
        <property name="testOnBorrow" value="true" />  
    </bean> 

    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> 
        <property name="hostName" value="localhost" /> 
        <property name="port" value="6379"/> 
        <property name="password" value="123"/> 
        <property name="poolConfig" ref="jedisPoolConfig" /> 
        <property name="usePool" value="true"/> 
    </bean> 

    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"   p:connection-factory-ref="jedisConnectionFactory" />

存储到磁盘

public class CacheFilter2 implements Filter {
	  private static ApplicationContext ctx;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		 HttpServletResponse resp = (HttpServletResponse) response;
	        HttpServletRequest req = (HttpServletRequest) request;
	       System.out.println(extName);
	        //判断主页
	        if (  req.getRequestURI().equals("/cn.car/login.jsp")==false) {       	
	        	chain.doFilter(request, resp);
	            return;
	        }   
	         String html = getHtmlFromCache();
	          if (null == html) {
	          MyResponseWrapper wrapper = new MyResponseWrapper(resp);
	            chain.doFilter(request, wrapper);
	            // 放入缓存
	            html = wrapper.getResult(); 
	            putIntoCache(html);
	        }
	        // 返回响应
	        resp.setContentType("text/html; charset=utf-8");
	        resp.getWriter().write(html);
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	
   public void setApplicationContext(ApplicationContext applicationContext) {
        this.ctx = applicationContext;
    }
 //取页面
    private String getHtmlFromCache() {
    	FileInputStream fis;
		try {
			File file = new File("D:\\webWork\\staticPage", "index.html");
			if(file.exists()){
				fis = new FileInputStream(file);
				InputStreamReader isr = new InputStreamReader(fis);
		    	BufferedReader br = new BufferedReader(isr);
		    	String line = br.readLine();
		    	StringBuffer sb = new StringBuffer(); 
		    	while(line != null){
		    		sb.append(line);
		    		line=br.readLine();
		    	}
		    	fis.close();
				return sb.toString();
			}
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}finally {
		
		}
    	
    }
 
    //存页面
    private void putIntoCache(String html) {
    	try {
			FileOutputStream fos = new FileOutputStream(new File("D:\\webWork\\staticPage","index.html"));
			fos.write(html.getBytes("utf-8"));
			fos.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

}

web中过滤器配置

<filter>
 <filter-name>cache</filter-name>
 <filter-class>cn.filter.CacheFilter</filter-class>
</filter>

  <filter-mapping>
    <filter-name>cache</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

猜你喜欢

转载自blog.csdn.net/qq_36677358/article/details/84855133
0条评论
添加一条新回复