0. Introduction
Why use caching? As website traffic grows, database IO will become a bottleneck early on, while using caching can cause database bottlenecks to arrive late, improving site performance. How does a Java Web project use caching? The cache is first to get the content returned to the page and then write to the cache (MemCached, Redis, and so on), this article uses MemCached as an example.
two. Code Examples
To intercept the content returned by the page, the overall idea is to write the original returned page content to a character writer, then assemble the string and parse it, and then return it to the client. The code is as follows:
For packaging Servletoutputstream:
public class Filterservletoutputstream extends servletoutputstream{ //Don't need too many methods, you can use OutputStream instead of private DataOutputStream stream; Public Filterservletoutputstream (OutputStream output) { stream = new DataOutputStream (output); } public void Write (int b) throws IOException { stream.write (b); } public void Write (byte[] b) throws IOException { stream.write (b); } public void Write (byte[] b, int off, int len) throws IOException { Stream.Write (b, off, Len);} }
Get the Content wrapper class:
Import Java.io.*;import java.util.arraylist;import Java.util.collection;import Java.util.linkedlist;import Java.util.list;import Java.util.map;import Java.util.treemap;import Javax.servlet.servletoutputstream;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservletresponse;import Javax.servlet.http.httpservletresponsewrapper;import Org.slf4j.logger;import org.slf4j.LoggerFactory;/** * Created by Zhuyb on 15/10/21. */public class Myhttpservletresponsewrapper extends Httpservletresponsewrapper implements serializable{private static Final long serialversionuid = -7207188787151521963l; private static final Logger LOG = Loggerfactory.getlogger (Myhttpservletresponsewrapper.class); private int statusCode = SC_OK; private int contentlength; Private String ContentType; Private final map<string, list<serializable>> headersmap = new treemap<string, list<serializable> > (String.case_insensitive_order); Private final List cookies = new ArrayList (); Private Bytearrayoutputstream outstr; Private PrintWriter writer; Private Boolean disableflushbuffer = true; /** * Creates a genericresponsewrapper * * public myhttpservletresponsewrapper (final HttpServletResponse respons e) {super (response); Output HTML results where this.outstr = new Bytearrayoutputstream (); }//Get Data public byte[] GetData () {if (writer! = null) Writer.flush (); return Outstr.tobytearray (); }/** * Gets the OutputStream. */Public Servletoutputstream Getoutputstream () {return new Filterservletoutputstream (OUTSTR); }/** * Sets the status code for this response. */public void SetStatus (final int code) {StatusCode = code; Super.setstatus (code); }/** * Send the error. If The response isn't OK, the most of the logic is bypassed and the error is sent Raw * Also, the content isn't cached. * * @param i the Status codE * @param string the error message * @throws IOException */public void senderror (int i, string string) th Rows IOException {statusCode = i; Super.senderror (i, string); }/** * Send the error. If The response isn't OK, the most of the logic is bypassed and the error is sent Raw * Also, the content isn't cached. * * @param i The Status code * @throws IOException */public void senderror (int i) throws IOException { StatusCode = i; Super.senderror (i); }/** * Send the redirect. If The response isn't OK, the most of the logic is bypassed and the error is sent raw. * Also, the content is not cached. * * @param string The URL to redirect to * @throws IOException */public void Sendredirect (string string) t Hrows IOException {statusCode = httpservletresponse.sc_moved_temporarily; Super.sendredirect (string); }/** * Returns The status code for this response. */ public int GetStatus () {return statusCode; }/** * Sets the content length. */public void setcontentlength (final int length) {this.contentlength = length; Super.setcontentlength (length); }/** * Gets the content length. */public int getcontentlength () {return contentlength; }/** * Sets the content type. */public void setContentType (final String type) {this.contenttype = type; Super.setcontenttype (type); }/** * Gets the content type. */Public String getContentType () {return contentType; }/** * Gets the print writer. Eventually write back to the browser using the output stream */public printwriter getwriter () throws IOException {if (writer = = null) {writer = new PrintWriter (New OutputStreamWriter (Getoutputstream (), getcharacterencoding ()), true); } return writer; }/** * @see Javax.servlet.http.httpservletresponsewrapper#addheader (Java.lang.StriNg, java.lang.String) */@Override public void AddHeader (string name, String value) {List<serializabl e> values = this.headersMap.get (name); if (values = = null) {values = new linkedlist<serializable> (); This.headersMap.put (name, values); } values.add (value); Super.addheader (name, value); }/** * @see javax.servlet.http.httpservletresponsewrapper#setheader (java.lang.String, java.lang.String) */ @Override public void SetHeader (string name, String value) {Final linkedlist<serializable> values = new L Inkedlist<serializable> (); Values.add (value); This.headersMap.put (name, values); Super.setheader (name, value); }/** * @see javax.servlet.http.httpservletresponsewrapper#adddateheader (java.lang.String, long) */@Overrid e public void Adddateheader (String name, long date) {list<serializable> values = this.headersMap.get (name); if (values = = null) {values = new linkedlist<serializable> (); This.headersMap.put (name, values); } values.add (date); Super.adddateheader (name, date); }/** * @see javax.servlet.http.httpservletresponsewrapper#setdateheader (java.lang.String, long) */@Overrid e public void Setdateheader (String name, long date) {final linkedlist<serializable> values = new Linkedli St<serializable> (); Values.add (date); This.headersMap.put (name, values); Super.setdateheader (name, date); }/** * @see javax.servlet.http.httpservletresponsewrapper#addintheader (java.lang.String, int) */@Override public void Addintheader (String name, int value) {list<serializable> values = this.headersMap.get (name); if (values = = null) {values = new linkedlist<serializable> (); This.headersMap.put (name, values); } values.add (VALue); Super.addintheader (name, value); }/** * @see javax.servlet.http.httpservletresponsewrapper#setintheader (java.lang.String, int) */@Override public void Setintheader (String name, int value) {Final linkedlist<serializable> values = new linkedlist& Lt Serializable> (); Values.add (value); This.headersMap.put (name, values); Super.setintheader (name, value); }/** * Adds a cookie. */public void Addcookie (final cookie cookie) {cookies.add (cookie); Super.addcookie (cookie); }/** * Gets all the cookies. */Public Collection getcookies () {return cookies; }/** * Flushes buffer and commits response to client. */public void Flushbuffer () throws IOException {flush (); Doing this might leads to response already committed exception//when the PageInfo have not yet built but the BU Ffer already flushed//happens in Weblogic when A servlet forward to a JSP page and the forward//method trigger a flush before it forwarded to the JSP// Disableflushbuffer for, purpose is ' true ' by default//EHC-447 if (!disableflushbuffer) {s Uper.flushbuffer (); }}/** * Resets the response. */public void Reset () {super.reset (); Cookies.clear (); Headersmap.clear (); StatusCode = SC_OK; ContentType = null; contentlength = 0; }/** * Resets the buffers. */public void Resetbuffer () {super.resetbuffer (); }/** * Flushes all the streams for this response. */public void flush () throws IOException {if (writer! = null) {Writer.flush (); } outstr.flush (); }/** * is the wrapped reponse ' s buffer flushing disabled? * @return True if the wrapped reponse ' s buffer flushing disabled */public boolean isdisableflushbuffer () { RetuRN Disableflushbuffer; }/** * Set If the wrapped reponse ' s buffer flushing should be disabled. * @param disableflushbuffer True if the wrapped reponse ' s buffer flushing should be disabled */public void Setdisa Bleflushbuffer (Boolean disableflushbuffer) {this.disableflushbuffer = Disableflushbuffer; }}
Cache Filters:
public class Cachefilter implements Filter {public void Destroy () {}public void init (Filterconfig filterconfig) throws Ser vletexception {}public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {httpservletrequest req = (httpservletrequest) request; HttpServletResponse res = (httpservletresponse) response; String FullUrl = Req.getrequesturl (). toString ()//with debug parameter not using cache, facilitates subsequent development debug if (Req.getparameter ("Debug")! = null) {C Acheble = false; Memcachedcachemanager.getcache ("Someproject_page_cache"). Put (Key, "");} String key = Fullurl.replaceall ("(\\?| &) Debug=1 "," "). Hashcode ();//If the page path contains Wenniuwuren, the Boolean cacheble =" Http://blog.csdn.net/wenniuwuren "is cached. Contains ("Wenniuwuren"); MemCached Pagecache = Memcachedcachemanager.getcache ("Jobmd_page_cache"), if (cacheble) {if (Pagecache! = null) { String html = (string) pagecache.get (key); if (Stringutils.isnotblank (HTML)) {Res.getwriter (). write (HTML); Return }//Use our custom response wrapper to wrap the original servletresponse myhttpservletresponsewrapper myhttpservletresponsewrapper = new MyH Ttpservletresponsewrapper (RES); Note that the myhttpservletresponsewrapper is passed in instead of the response parameter to get the page return content Chain.dofilter (req, MYHTTPSERVLETRESPONSEWR Apper); if (myhttpservletresponsewrapper.getstatus () = = 0 | | myhttpservletresponsewrapper.getstatus () = =) {if (MyH Ttpservletresponsewrapper.getdata (). length > 0) {String data = new String (myhttpservletresponsewrapper. GetData ()); Of course, before this can be customized processing data, and then back to the browser. Page decoration frame Sitemesh, that is, after the HTML decoration processing returned to the page//write to the browser res.getwriter (). write (data); Cache, Cache 7,200 seconds Pagecache.put (key, data, 7200); Return } else {//No data, cache empty pagecache.put (key, ""); Chain.dofilter (request, response); } } } else {//no cache will continue to execute Chain.dofilter (request, response); }} else {//does not cache the processing flow of the page if (Fullurl.contains ("debug=1")) {Pagecache.remove (key); } chain.dofilter (request, Response);}}}
Web. XML Config filter:
<filter> <filter-name>cache</filter-name> <filter-class> com.wenniuwuren.cachefilter</filter-class> <init-param> <param-name>cachepath</ param-name> <param-value>/var/cache/project</param-value> </init-param></ filter><filter-mapping> <filter-name>cache</filter-name> <url-pattern>*.* </url-pattern></filter-mapping>
get results such as: Outstr gets the HTML code returned by the page:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Get back the contents of the browser--java cache usage