redisキャッシュを使用したWebサイトのトップページ

7806 ワード

一、会社は私にredisキャッシュのウェブサイトのホームページとH 5バージョンのホームページに必要なjsonデータを使うように要求して、ウェブサイトのホームページはjspを通じて動的に生成しました.だから、フィルタを書いてwebコンテナがhtmlページを生成する前にredisに保存したいと思っています.具体的なコードは以下の通りです.
ホームページ
1、カスタム包装類
               

public class CacheHtmlResponseWrapper extends HttpServletResponseWrapper {

    //       html
    private PrintWriter cachedWriter;
    private CharArrayWriter bufferedWriter;
    
	 public CacheHtmlResponseWrapper(HttpServletResponse response) {
	        super(response);
	        //       
	        bufferedWriter = new CharArrayWriter();
	        cachedWriter = new PrintWriter(bufferedWriter);
	    }
	 
	 @Override
	    public PrintWriter getWriter() {
	        return cachedWriter;
	    }
	 
	    public String getResult() {
	        return bufferedWriter.toString();
	    }
	 
}

2、フィルターで使う
      

    public class HtmlToRedisFilter implements Filter{

	private static Logger logger = LoggerFactory.getLogger(HtmlToRedisFilter.class);
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpServletRequest req = (HttpServletRequest) request;
		Cookie[] cookies = req.getCookies();
		String name = null;
		//      
		
		//       
		if (name==null){
			//   ,      
			String html =null;
			ShardedJedis shardedJedis =null;
			try{
				shardedJedis = RedisShardUtils.getShardedJedis();
				html = shardedJedis.get("index_nologin");
				if (null == html){
					//       
					//    html     
					CacheHtmlResponseWrapper wrapper = new CacheHtmlResponseWrapper(resp);
					filterChain.doFilter(req, wrapper);
					html = wrapper.getResult();
					RedisShardUtils.toRedisPC("index_nologin", html);
				}
			}catch(Exception e){
				//        ,  
				filterChain.doFilter(req, resp);
				logger.debug("redis      ");
				return;
			}finally{
				if(shardedJedis!=null)
				   RedisShardUtils.returnShardedJedis(shardedJedis);
			}
			//     
			resp.setContentType("text/html; charset=utf-8");
			resp.getWriter().print(html);
		}else{
			//        
			filterChain.doFilter(req, resp);
		}
	}
	public void init(FilterConfig arg0) throws ServletException {

	}
	public void destroy() {

	}
}

     
3.redisスライス接続プール
         

  public class RedisShardUtils {
	
	private static ShardedJedisPool shardedJedisPool;
	public static int nologin_pc_cachetime=12;
	public static int nologin_phone_cachetime=12;
	
	private static Logger logger = LoggerFactory.getLogger(RedisShardUtils.class);
    
	static {
		ResourceBundle bundle = ResourceBundle.getBundle(RedisConstants.REDIS_PATH);
		if (bundle == null) {
			logger.debug("[redisshard.properties] is not found!");
		}
		//      
		nologin_pc_cachetime=Integer.valueOf(bundle.getString(RedisConstants.NOLOGIN_PC_CACHETIME));
		nologin_phone_cachetime=Integer.valueOf(bundle.getString(RedisConstants.NOLOGIN_PHONE_CACHETIME));
		System.out.println(nologin_phone_cachetime);
		//   
		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		config.setMaxTotal(Integer.valueOf(bundle.getString(RedisConstants.REDIS_POOL_MAXACTIVE)));
		config.setMaxIdle(Integer.valueOf(bundle.getString(RedisConstants.REDIS_POOL_MAXIDLE)));
		config.setMaxWaitMillis(Long.valueOf(bundle.getString(RedisConstants.redis_pool_maxWait)));
		config.setTestOnBorrow(Boolean.valueOf(bundle.getString(RedisConstants.REDIS_POOL_TESTONBORROW)));
		config.setTestOnReturn(Boolean.valueOf(bundle.getString(RedisConstants.REDIS_POOL_TESTONRETURN)));

		//  redis          
		JedisShardInfo server01 = new JedisShardInfo(bundle.getString(RedisConstants.REDIS_IP01),
				Integer.valueOf(bundle.getString(RedisConstants.REDIS_PORT01)));
		
		ArrayList servers = new ArrayList();
		servers.add(server01);

		//                              
		shardedJedisPool = new ShardedJedisPool(config, servers);
	}

	//       
	public static ShardedJedis getShardedJedis() {
		return shardedJedisPool.getResource();
	}

	//       
	public static void returnShardedJedis(ShardedJedis shardedJedis) {
		shardedJedisPool.returnResourceObject(shardedJedis);
	}
	
	//     
	public static void delRedisKey(String key1,String key2) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = RedisShardUtils.getShardedJedis();
			shardedJedis.del(key1);
			shardedJedis.del(key2);
		} catch (Exception e) {
			logger.debug("redis         ");
		} finally {
			if (shardedJedis != null)
				RedisShardUtils.returnShardedJedis(shardedJedis);
		}
	}
	
	//     redis 
	public static void toRedisPhone(String key,String value){
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = RedisShardUtils.getShardedJedis();
			shardedJedis.setex(key, 60*60*nologin_phone_cachetime, value);
		} catch (Exception e) {
			logger.debug("redis         ");
		} finally{
			if (shardedJedis != null)
				RedisShardUtils.returnShardedJedis(shardedJedis);
		}
	}
	//     redis 
	public static void toRedisPC(String key,String value){
			ShardedJedis shardedJedis = null;
			try {
				shardedJedis = RedisShardUtils.getShardedJedis();
				shardedJedis.setex(key, 60*60*nologin_pc_cachetime, value);
			} catch (Exception e) {
				logger.debug("redis         ");
			} finally {
				if (shardedJedis != null)
					RedisShardUtils.returnShardedJedis(shardedJedis);
			}
		}
	
	//   
	public static String getCache(String key){
		ShardedJedis shardedJedis = null;
		String cache=null;
		try {
			shardedJedis = RedisShardUtils.getShardedJedis();
		    cache = shardedJedis.get(key);
		} catch (Exception e) {
			logger.debug("redis         ");
		} finally {
			if (shardedJedis != null)
				RedisShardUtils.returnShardedJedis(shardedJedis);
		}
		
		return cache;
	}

}

        
4、H 5バージョンはjsonデータのカスタムパッケージクラスを返す
  

public class CacheJsonResponseWrapper extends HttpServletResponseWrapper {

    private PrintWriter cachedWriter;
    private ByteArrayOutputStream bufferedWriter;
    private ServletOutputStream out=null;
    
    //    
	public CacheJsonResponseWrapper(HttpServletResponse response) throws IOException {
	        super(response);
	        //       
	        bufferedWriter = new ByteArrayOutputStream();
	        out=new WrapperOutputStream(bufferedWriter);
	        //  PrintWriter ,       PrintWriter   bufferedWriter
	        cachedWriter = new PrintWriter(bufferedWriter);
	    }
	
	//      writer   
	public PrintWriter getWriter()throws UnsupportedEncodingException{
		return cachedWriter;
	}
	//     outputStream  
	public ServletOutputStream getOutputStream()throws IOException{
		return out;
	}
	//     flushBuffer  
	public void flushBuffer() throws IOException {
		if(out!=null){
			out.flush();
		}
		if(cachedWriter!=null){
			cachedWriter.flush();
		}
	}
	public void reset() {
		bufferedWriter.reset();
	}
	//    
	public String getResult()throws IOException {
		flushBuffer();
		return new String(bufferedWriter.toByteArray(),"utf-8");
	}
	//    ServletOutputStream    
	private class WrapperOutputStream extends ServletOutputStream {
		private ByteArrayOutputStream bos=null;
		public WrapperOutputStream(ByteArrayOutputStream stream)throws IOException{
			bos=stream ;
		}
		public void write(int b)throws IOException{
			bos.write(b);
		}
	}
	
}

まとめ:本システムはspringmvcを使用し、ウェブサイトバージョンjspはhtmlを生成し、H 5バージョンはjsonデータを返し、包装類は異なる.