SPRINGMVC Cache Home page with Redis

Source: Internet
Author: User
Tags redis server

First, the purpose of caching the home page is not to improve performance, but to reduce database access pressure and effectively delay the arrival of database I/O bottlenecks. There are many ways to implement the home page cache, but since Redis is used in the project to cache database reads and writes, you can also cache the home page by the way.

Implementation ideas

Write a filter that blocks access requests to the home page in the filter. The Redis server is queried for the cache of the home page HTML, and if so, it is returned directly to the client, and if not, intercepts the render result of the JSP in the filter and puts it in the Redis cache for the next use. We set the cache expiration time to 10 minutes.

Realize

There are two points to be aware of to achieve:

    1. How to use the Spring container in a servlet filter
    2. How to intercept JSP render results

For question one, you can see my other blog: Using the Spring container in the servlet filter
For question two, we can inherit the HttpServletResponseWrapper class to implement it smartly:

 Public  class responsewrapper extends httpservletresponsewrapper {    PrivatePrintWriter Cachedwriter;PrivateChararraywriter BufferedWriter; Public Responsewrapper(HttpServletResponse response) {Super(response);//This is where we save the returned results.BufferedWriter =NewChararraywriter ();//This is a wrapper printwriter, so that all results are written to bufferedwriter through this printwriterCachedwriter =NewPrintWriter (BufferedWriter); }@Override     PublicPrintWritergetwriter() {returnCachedwriter; }/** * Gets the original HTML page content. * * @return  * *     PublicStringGetResult() {returnBufferedwriter.tostring (); }}

Then use the class in the filter:

 Public  class cachefilter implements Filter, applicationcontextaware  {    Private Static FinalLogger log = Loggerfactory.getlogger (Cachefilter.class);Private StaticApplicationContext CTX;@Override     Public void Init(filterconfig config)throwsServletexception {}@Override     Public void DoFilter(ServletRequest servletrequest, Servletresponse servletresponse, Filterchain filterchain)throwsIOException, servletexception {HttpServletResponse resp = (httpservletresponse) servletresponse; HttpServletRequest req = (httpservletrequest) servletrequest;//If you are not visiting the homepage, release        if(false= = Req.getrequesturi (). Equals ("/") {Filterchain.dofilter (ServletRequest, RESP);return; }//access to the homepage        //Get the home page HTML from the cacheString html = Gethtmlfromcache ();if(NULL= = html) {//The cache does not have            //Intercept generated HTML and put in cacheLog.info ("Cache does not exist, generate cache"); Responsewrapper wrapper =NewResponsewrapper (RESP);* * * * * The above code is executed before request is processed * * * *Filterchain.dofilter (ServletRequest, wrapper);* * * * * * * * The following code is executed before the request is processed * * *            //Put cachehtml = Wrapper.getresult ();        Putintocache (HTML); }//Return responseResp.setcontenttype ("text/html; Charset=utf-8 ");    Resp.getwriter (). print (HTML); }@Override     Public void Destroy() {    }@Override     Public void Setapplicationcontext(ApplicationContext ApplicationContext)throwsbeansexception { This. CTX = ApplicationContext; }PrivateStringGethtmlfromcache() {Stringredistemplate Redis = (stringredistemplate) Ctx.getbean ("Redistemplate");returnRedis.opsforvalue (). Get ("Home"); }Private void Putintocache(String HTML) {Stringredistemplate Redis = (stringredistemplate) Ctx.getbean ("Redistemplate"); Redis.opsforvalue (). Set ("Home", HTML, TimeUnit.MINUTES.toSeconds (Ten));//10 min}}

According to this logic, when the client's GET request is made / , the HTML code of the CacheFilter home page is first fetched to the Redis originating request, and if successful, it is returned directly to the client and fails, then it is put in by the rendering result of the newly-written ResponseWrapper intercept home jsp. Redis and set the expiration time to 10 minutes. This allows the next request to be read directly from the cache, without having to go through Controller Service such a Dao Database cumbersome process.

SPRINGMVC Cache Home page with Redis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.