Small white web Optimization road One, using Redis to cache information

Source: Internet
Author: User

As a web developer, it is clearly not our only goal to complete an application according to the needs of the product manager, and many times we consider not only the requirements, but the performance bottlenecks that come after the project goes live. Many Web applications may encounter slow response problems when they go online, and from today on, I will take a simple example to lead you to optimize the Web application step-by-step.

Give me a chestnut first:

Small white when making a Web list page, the requirements are simple, when the user visits the first page, the server returns 1-10 article introduction data, the 2nd page, the server returned 11-20 article introduction data. Small white then thought, this simple ah, each front end give me a page on line, I directly from the database to find out, and then back to the line. Haha, so easy!

When the small white program is written on line, with the increase of users and articles, database pressure is greater, for example, when the number of articles reached 1 million, each time the paging query requires time-consuming database of about 500ms, when the small white realized that the program needs to be optimized.

This time the small white teacher came, the teacher said, these articles list data, in a short period will not change too big, why not to cache it up? This can be removed from memory every time, without having to access the database every time.

The project architecture is made up of the simplest

Added the cache layer:

In this way, the speed of access can be greatly accelerated.

For this example, you can cache the list confidence you get every time you obtain it, and you can set the list cache to expire in 1 minutes, so that the number of visits in 1 minutes will be greatly improved.

As for caching, you can use Redis, whichis a high-performance Key-value database. can be a good complement to the relational database.

Xiao Bai after listening to the teacher gave advice, immediately set to start to build the Redis development environment, and began to develop, he wrote a demo, this demo, using the cache before each access speed of 400-500ms, using the cache after the speed of access stability in 25-27ms, Equivalent to 17 times times the speed increase!

The following is the main test code:

Package Com.happyheng.controller;import Com.alibaba.fastjson.json;import Com.happyheng.dao.articledao;import Com.happyheng.model.article;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.util.stringutils;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import Redis.clients.jedis.jedis;import java.util.List;/* * * * * * Created by Happyheng on 17/5/6. */@RestController @requestmapping ("/test") public class TestController {private static final String key_cache_article_l    IST = "Article_list";    @Autowired private Articledao Articledao; @RequestMapping ("/testselectfromdb") public list<article> Testselectfromdb () throws Exception {return art    Icledao.getarticlelistfromdb (); } @RequestMapping ("/testselectfromcache") public String Testselectfromcache () throws Exception {Jedis Jedis        = new Jedis ("localhost"); First remove data from cache String ArtIcleliststr = Jedis.get (key_cache_article_list); if (!        Stringutils.isempty (ARTICLELISTSTR)) {return articleliststr; } else {//If the data is empty, then taken out of the DB, then serialized and then written to the cache, and set the expiration time of 1 minutes list<article> articlelist = Articleda            O.getarticlelistfromdb ();            String serializearticleliststr = json.tojsonstring (articlelist);            Jedis.set (Key_cache_article_list, SERIALIZEARTICLELISTSTR);            Jedis.expire (Key_cache_article_list, 60);        return serializearticleliststr; }    }}

Package Com.happyheng.dao;import Com.happyheng.model.article;import Org.springframework.stereotype.service;import Java.sql.*;import Java.util.arraylist;import java.util.list;/** * * * Created by Happyheng on 17/5/7. */@Servicepublic class Articledao {public list<article> Getarticlelistfromdb () throws exception{String s        QL = "SELECT * from article ORDER by Create_time DESC LIMIT 0, 10";        Class.forName ("Com.mysql.jdbc.Driver"); Connection mconnection = drivermanager.getconnection ("jdbc:mysql://localhost:3306/optimize_db", "root", "Mytestcon"        );        Statement Statement = Mconnection.createstatement ();        ResultSet ResultSet = statement.executequery (sql);            try {list<article> List = new arraylist<> ();            Note that the pointer is at the beginning of the -1 position, this line next () method, will first determine whether the next position has, if any, point to the next position.                while (Resultset.next ()) {Article Article = new article ();                Article.setid (Resultset.getlong ("id")); Article.sEttitle (resultset.getstring ("title"));                Article.setcontent (resultset.getstring ("content"));                Article.setcreate_time (resultset.getstring ("Create_time"));            List.add (article);        } return list;        } catch (Exception e) {e.printstacktrace ();                } finally {try {resultset.close ();                Statement.close ();            Mconnection.close ();            } catch (SQLException e) {e.printstacktrace ();    }} return null; }}

As you can see, when you access Testselectfromdb, you get the data directly from the database, when you access Testselectfromcache, you get the data from the cache, if not, get the data from the database, and then write to the cache. The following is a comparison of access times for two access methods:

Direct access to DB:



To access the cache:




Small white web Optimization road One, using Redis to cache information

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.