SpringMVC implements cache homepage through Redis

Source: Internet
Author: User

SpringMVC implements cache homepage through Redis

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

Implementation

Write a filter to intercept access requests to the home page. Query the html cache of the homepage from the Redis server. If yes, return it directly to the client. If no, capture the rendering result of JSP in the filter and put it in the Redis cache for the next use. We set the cache expiration time to 10 minutes.

Implementation

Note the following two points for implementation:

How to intercept JSP rendering results using Spring containers in the Servlet transfer Handler

For question 1, see my other blog: Using Spring containers in Servlet Filter.
For question 2, we can inheritHttpServletResponseWrapperClass:

Public class ResponseWrapper extends HttpServletResponseWrapper {private PrintWriter cachedWriter; private CharArrayWriter bufferedWriter; public ResponseWrapper (HttpServletResponse response) {super (response ); // This is where we save the returned result bufferedWriter = new CharArrayWriter (); // This is the packaging of PrintWriter, write all results to bufferedWriter through this PrintWriter. cachedWriter = new PrintWriter (bufferedWriter);} @ Override public Prin TWriter getWriter () {return cachedWriter;}/*** get the original HTML page content. ** @ Return */public String getResult () {return bufferedWriter. toString ();}}

Then use this class in the filter:

Public class CacheFilter implements Filter, ApplicationContextAware {private static final Logger log = LoggerFactory. getLogger (CacheFilter. class); private static ApplicationContext ctx; @ Override public void init (FilterConfig config) throws ServletException {}@ Override public void doFilter (ServletRequest servletRequest, includid, FilterChain filterChain) throws IOException, servletException {HttpServletResponse resp = (HttpServletResponse) servletResponse; HttpServletRequest req = (HttpServletRequest) servletRequest; // if you are not visiting the homepage, open if (false = req. getRequestURI (). equals ("/") {filterChain. doFilter (servletRequest, resp); return ;}// access the homepage // obtain the homepage html String html = getHtmlFromCache () from the cache; if (null = html) {// No html generated in the cache is intercepted and put into the cache log.info ("cache does not exist, cache generated"); ResponseWrapper wrapper = new ResponseWrapper (resp ); // *** run the *** filterChain command before the request is processed. doFilter (servletRequest, wrapper); // ***** the following code is executed before the request is processed ***** // The code is cached in html = wrapper. getResult (); putaskcache (html);} // returns the response resp. setContentType ("text/html; charset = UTF-8"); resp. getWriter (). print (html) ;}@ Override public void destroy () {}@ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {this. ctx = applicationContext;} private String getHtmlFromCache () {StringRedisTemplate redis = (StringRedisTemplate) ctx. getBean ("redisTemplate"); return redis. opsForValue (). get ("home");} private void put1_cache (String html) {StringRedisTemplate redis = (StringRedisTemplate) ctx. getBean ("redisTemplate"); redis. opsForValue (). set ("home", html, TimeUnit. MINUTES. toSeconds (10); // 10 minutes }}

According to this logic, when the customer'sGETThe request is/,CacheFilterFirstRedisInitiate a request to obtain the html code of the homepage. If the code is successful, it is directly returned to the client. If the Code failsResponseWrapperIntercept the rendering result of the homepage JSP and put it inRedisAnd set the expiration time to 10 minutes. In this way, the next request can be directly read from the cache without passing throughController->Service->Dao->DatabaseThis is a very troublesome process.

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.