java代码片:网站缓存数据到tomcat服务器
通过缓存使相同的数据不用重复加载,降低数据库的访问
public class CacheFilter implements Filter { //实例变量【每线程共享】 private Map<String,byte[]> cache=new HashMap<String , byte[]>(); @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest) req; HttpServletResponse response=(HttpServletResponse) res; // 1、取得客户端访问路径 String uri=request.getRequestURI(); // 2、根据URL去缓存中查询对应的页面资源 byte[] data=cache.get(uri); // 3、如果没有就放行到web资源中 if(data==null){ MyResponse myResponse=new MyResponse(response); chain.doFilter(request, response); // 4、返回后将缓存数据放到缓存中,便于下次使用 data=myResponse.getBuffer(); // 6、向浏览器输出 cache.put(uri, data); System.out.println("从服务端获取资源"); }else{ // 5、如果有,就直接从缓存中取得数据 System.out.println("从缓存读取"); chain.doFilter(request, response); } } @Override public void init(FilterConfig arg0) throws ServletException { } }
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ShowServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream sout=response.getOutputStream(); sout.write("fgfgdfsgdsfgdsfgdsfgdsfgsdfgdsdsfgdsfgsdfgdsfgsdfgkjslkdfjgl;kdsjglsdjfglsdjfgldfsjglksdfjgsfdl".getBytes()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }