redis notes

target

  • Be able to tell the common data types of redis

  • You can use redis's string operation command

  • Can use the hash operation command of redis

  • You can use the list operation command of redis

  • You can use the set operation command of redis

  • You can use the zset operation command of redis

  • Redis can be operated using jedis

  • Understand Redis persistence

1. Basic concepts of NoSQL

1.1 what is NOSQL

NoSQL(NoSQL = Not Only SQL), which means "not just SQL", is a new database concept, generally referring to non relational databases.

1.2 mainstream NOSQL products

  • Key value storage database Redis

  • Column storage database (distributed)

  • Document database (Web application is similar to key Value, and Value is structured) Mongo DB

  • Graph database (graph structure)

1.3 characteristics of NoSQL

It has incomparable performance advantages over relational database in big data access, such as:

  • Easy to expand

    There are many kinds of NoSQL databases, but one common feature is to remove the relational characteristics of relational databases. There is no relationship between data, so it is very easy to expand. It also brings scalability at the architecture level.

  • Large amount of data, high performance

        NoSQL All databases have very high read-write performance, especially in the case of large amount of data, which is due to its irrelevance, simple database structure and accessing data in memory.
    
  • Flexible data model

NoSQL does not need to create fields for the data to be stored in advance, and can store custom data formats at any time. In relational databases, adding and deleting fields is a very troublesome thing. If it is a table with a very large amount of data, adding fields is a nightmare. This is particularly obvious in the era of Web 2.0 with a large amount of data.

  • High availability

    NoSQL can easily implement high availability architecture without affecting performance. For example, Cassandra and HBase model can also achieve high availability through replication model.
    1.4. Why learn NoSQL

    • High concurrent read and write
    • Massive data query efficiency
    • High scalability, high availability

    2. Overview of redis

    2.1 related knowledge of relational database

2.2. What is Redis

Redis is an open source high-performance key value pair developed in C language The data in the database is stored in memory. The official provides test data. 50 concurrent 100000 requests are executed. The reading speed is 110000 times / s and the writing speed is 81000 times / s. redis provides a variety of key value data types to meet the storage requirements in different scenarios. At present, the key value data types supported by redis are as follows:

  • String type string (most commonly used)
  • Hash type hash
  • List type list
  • Set type set
  • Ordered set type sortedset

2.3 application scenarios of redis

  • Cache (data query, short connection, news content, commodity content, etc.)
  • Task queue. (second kill, rush purchase, 12306, etc.) – > hash
  • Data expiration processing (accurate to milliseconds, SMS verification code)
  • The session in the distributed cluster architecture is separated from the session server
  • Chat room online friends list
  • App Leaderboard
  • Website access statistics ----- > Set

2.4 default port and password of redis

Port: 6379. No password is required by default

How to install redis in linux?

  1. Installing a c + + environment in a virtual machine
yum -y install gcc-c++
  1. Download Redis
    Link: https://pan.baidu.com/s/1EXlFF_tn_yqTy5SNatoE1w
    Extraction code: vj7s
  2. Upload to Linux
  3. decompression
tar -zxf redis-4.0.14.tar.gz
  1. compile
cd redis-4.0.14
make
  1. Create a directory
mkdir /usr/local/redis
  1. install
make install PREFIX=/usr/local/redis
  1. Enter the installed redis directory and copy the configuration file
cd /usr/local/redis/bin
cp /root/redis-4.0.14/redis.conf  /usr/local/redis/bin      -- The purpose of this command is to redis-4.0.14 Medium redis.conf Copy files to bin catalogue
  1. Modify profile
# Modify profile
vi redis.conf
# Redis background startup
 modify daemonize by yes
# Redis server can be accessed across networks 
modify bind Is 0.0.0.0
# Enable aof persistence. This can be omitted
appendonly yes
  1. Start redis
./redis-server redis.conf
  1. If you want to connect to redis remotely, you must release port 6379

3.Redis data type

3.1 redis data type

The data stored in redis exists in the form of key value. Value supports five data types. In daily development, four types are mainly used: string, hash, string list and string set, of which the most commonly used is string type.

String (String)

Hash is similar to HashMap

String list

A string set is similar to a HashSet

Ordered string set (sorted set or zset)

3.2 key

  • key should not be too long (not more than 1024 bytes)

  • Not too short. Poor readability

    Project name:modular:key  eg: mm:user:name
    

    4 redis----->String

4.1 General

string is the most basic type of redis and is used most frequently. A key corresponds to a value. A key can store 512MB at most

4.2 application scenarios

  1. Caching function: the most classic use scenario of string. Redis is used as the cache layer and Mysql as the storage layer. Most of the requested data is operated in redis. Because redis supports high concurrency, caching can usually accelerate reading and writing and reduce the pressure on the back end.

  2. Counter function: such as video playback times and likes.

  3. ID increment

4.3 common commands

commanddescribe
Set key valueSet the value of the specified key
Get key (key)Gets the value of the specified key
DEL keyDelete key
GETSET key valueSet the value of the given key to value and return the old value of the key.
Set key seconds valueAssociate the value value with the key and set the expiration time of the key to seconds (in seconds).
SETNX key valueThe key value can only be set when the key does not exist.
Incr key (key)Increment the numeric value stored in the key by one.
INCRBY key incrementAdd the value stored by the key to the given increment value.
DECR keySubtract the numeric value stored in the key by one.
DECRBY key decrementkey subtracts the given decrement from the stored value.

4.4 application examples

The commodity number and order number are generated by the incrementing numerical feature of string.

Define item number key: product:id
192.168.101.3:7003> INCR product:id
(integer) 2
192.168.101.3:7003> INCR product:id
(integer) 3

5.redis------->Hash

5.1 general

hash in Redis is a collection of key value pairs.

Redis hash is a mapping table of field and value of string type. Hash is especially suitable for storing objects.

Redis storage hash can be regarded as a map container of String key and String value, that is, the values can be regarded as a map collection

It is especially suitable for storing objects. Compared with storing an object type in Hash type, it occupies less memory space and is convenient to access the whole object than storing it in String type

5.2 application scenarios

Use an object to store user information, product information, order information, etc.

5.3 common commands

commandCommand description
hset key filed valueSet the value of the field field in the hash table key to value
hmset key field1 value1 [field2 value2]... (emphasis)Set multiple field value pairs to the hash table key at the same time
hget key filedGets the value of the specified field stored in the hash table
hmget key filed1 filed2 (key)Gets the value of more than one given field
hdel key filed1 [filed2] (key)Delete one or more hash table fields
hlen keyGets the number of fields in the hash table
del keyDelete the entire hash (object)
HGETALL key (key)Gets all fields and values of the specified key in the hash table
HKEYS keyGets the fields in all hash tables
HVALS keyGets all values in the hash table

Summary

  1. Hash is a key value pair, similar to the HashMap in Java
  2. It is especially suitable for storing objects and facilitating the operation of a field in the object

6.redis------->list

ArrayList uses array to store data, so it is fast to query data according to index, and displacement operation needs to be designed when adding or deleting elements, so it is slow.

LinkedList uses a two-way linked list to store data. Each element records the pointers of the front and rear elements, so when inserting and deleting data, you can only change the pointers of the front and rear elements, which is very fast. Then, when querying elements through subscripts, it needs to index from the beginning, so it is relatively slow, but it is faster to query the first or last elements.

6.1 general

List type (list) can store an ordered string list (linked list). The common operation is to add elements to both ends of the list or obtain a fragment of the list.
The internal of the list type is implemented using a double linked list, so the time complexity of adding elements to both ends of the list is 0 (1), and the faster it is to get the elements closer to both ends. This means that even for a list with tens of millions of elements, it is extremely fast to get 10 records at the head or tail.

6.2 application scenarios

Such as friends list, fans list, message queue, latest news ranking, etc.

The rpush method is equivalent to putting messages into the queue, and lpop/rpop is equivalent to taking messages from the queue for consumption

6.3. Common commands

commandCommand description
lpush key value1 value2... (emphasis)Inserts one or more values into the list header (left)
rpush key value1 value2... (emphasis)Add one or more values to the list (right)
Lpop key (key)Pop up one on the left is equivalent to removing the first one
Rpop key (key)Pop up one on the right is equivalent to removing the last one
llen keyReturns the number of elements in the list corresponding to the specified key
LINDEX key indexGet elements in the list by index
LINSERT key BEFORE| AFTER pivot valueInserts an element before or after an element in the list

6.4 application examples

Product review list

  • Idea: create a commodity comment list in redis, users publish commodity comments, convert the comment information into json and store it in the list. The user queries the comment list on the page, and takes out json data from redis and displays it on the page.

Summary

  1. List is a string linked list. Both left and right can be inserted and added;
  2. If the key does not exist, create a new linked list;
    If the key already exists, add content;
    If all values are removed, the corresponding key disappears.
    The operation of linked list, both head and tail, is very efficient, but if it is the operation of intermediate elements, the efficiency is general

    7.redis------->set

    7.1 general

Redis Set is an unordered Set of string type. Collection members are unique, which means that duplicate data cannot appear in the collection.

Collections in Redis are implemented through hash tables, so the time complexity of adding, deleting and searching is O(1). The largest number of members in the set is the 32nd power of 2 - 1 (4294967295, each set can store more than 4 billion members).

Redis also provides the operations of intersection, union and difference sets between multiple sets

Features: disorder + uniqueness

7.2 application scenarios

Voting records

Common friends, common interests, category labels

7.3. Common commands

commandCommand description
sadd key member1 [member2] (key)Add one or more members to the collection
srem key member1 [member2]Remove one or more members
smembers keyReturn all members in the collection and view all
SCARD keyGets the number of members of the collection
SPOP keyRemoves and returns a random element in the collection
SDIFF key1 [key2] (key)Returns the difference set of all given sets
Sun key1 [key2]Returns the union of all given sets
SINTER key1 [key2]Returns the intersection of all given sets

Difference set: if the first set has some, and the second set does not, which is the first, which is the standard.

7.4 application examples

Common friends

  • A's friends
  • B's friends
  • A and B's mutual friends

Summary

  1. The Set in Redis is invalid + unique, similar to the HashSet in Java
  2. application
    • Voting records
    • Calculate the difference

      8. Redis -- > -- > sorted set Zset

      8.1 general

Redis ordered collections, like collections, are collections of string elements, and duplicate members are not allowed.

The difference is that each element is associated with a score of type double. redis sorts the members of the collection from small to large through scores.

Members of an ordered set are unique, but scores can be repeated.

Collection is implemented through hash table, so the complexity of adding, deleting and searching is O(1). The largest number of members in the collection is 232 - 1 (4294967295, each collection can store more than 4 billion members).

Features: ordered (sorted by score) + unique

8.2 application scenarios

Leaderboard: for example, video websites need to make leaderboards for videos uploaded by users

8.3. Common commands

commandCommand description
ZADD key score member [score member...] (key)Add element
ZSCORE key memberGets the score of the element
ZREM key member [member ...]Delete element
ZCARD keyGets the number of elements in the collection
Zrange key start stop [with scores]Get a list of elements ranked in a range
ZREVRANGE key start stop (key)Sort by score from high to low

8.4 application examples

Commodity sales ranking

  • Demand: ranking display of commodities according to commodity sales volume
  • Idea: define the sorted set. The Key is items:sellsort, and the score is the sales volume of goods
  • realization:
--The sales volume of item 1001 is 9 and the sales volume of item 1002 is 10
ZADD items:sellsort 9 1001 10 1002		

--Sales volume of item No. 1001 plus 1
ZINCRBY items:sellsort 1 1001

--Top 10 commodity sales()
ZREVRANGE items:sellsort 0 9

Summary

  1. ZSet: ordered Set
    • Features: orderly + unique
  2. Application scenario: Leaderboard

Redis's general operations, publishing, subscribing and persistence

Knowledge points - Redis general operations (understand)

1. Objectives

  • Master the general operation commands of Redis

2. Path

  • General operation
  • Multi database

3. Explanation

3.1 general operation

  • keys *: query all key s

  • exists key: determines whether there is a specified key. If yes, it returns 1; otherwise, it returns 0

  • expire key seconds: sets the lifetime of this key in the cache (important)

  • ttl key: displays the remaining time of the specified key

    If the return value is - 1: never expire

    If the return value is - 2: it has expired or does not exist

  • del key: delete the specified key (important)

  • rename key: Rename

  • type key: determine the type of a key

  • ping: test whether the connection is connected

3.2 multi database

redis has 16 databases by default, with numbers ranging from 0 to 15. [default is database 0]

  • select index: switch Libraries
  • move key index: move the key to the library number (index is the library number)
  • flushdb: empty the current database
  • Flush: clear all databases under the current instance

4. Summary

  1. exists key determines whether this key exists
  2. expire key seconds sets the lifetime of this key in the cache
  3. ttl key displays the remaining time of the specified key
  4. select index switch Library

Knowledge points - persistence of Redis [interview]

1. Objectives

Redis's high performance is due to the fact that all data is stored in memory. In order to ensure that data is not lost after redis is restarted, data needs to be synchronized from memory to hard disk (file). This process is persistence.

Redis supports persistence in two ways: RDB and AOF. One of them can be used alone or in combination.

2. Path

  • RDB persistence mechanism
  • AOF persistence mechanism
  • Comparison of two persistence mechanisms

3. Explanation

3.1 RDB persistence mechanism

3.1.1 general

RDB persistence refers to writing a dataset snapshot in memory to disk within a specified time interval. This method is to write the data in memory to the binary file in the form of snapshot. The default file name is dump.rdb. This method is enabled by default and does not need to be configured

3.1.2 RDB persistence mechanism configuration
  • The following configurations are available in the redis.windows.conf configuration file:

Among them, the above configuration is the RDB data persistence time:

keywordTime (seconds)key modify quantityexplain
save9001dump memory snapshot if at least one key changes every 900 seconds (15 minutes)
save30010dump the memory snapshot if at least 10 key s change every 300 seconds (5 minutes)
save6010000dump memory snapshot if at least 10000 key s change every 60 seconds (1 minute)

3.2 AOF persistence mechanism

3.2.1 general

The AOF persistence mechanism will append each received write command to the file through the write function. The default file name is appendonly.aof. This method is not enabled by default and needs to be configured when it is used

3.2.2 AOF persistence mechanism configuration
3.2.2.1 enable configuration
  • The following configurations are available in the redis.windows.conf configuration file:

  • Change appendonly to yes, but you need to specify this file when you start redis, which means you can't click directly. You need to enter the command to start:

  • After the AOF persistence mechanism is enabled, an appendonly.aof file will be generated in the directory by default

3.2.2.2 configuration details
  • The above configuration is the time for aof persistence, which is explained as follows: (configured on redis.windows.conf)
keywordPersistence timingexplain
appendfsyncalwaysThe update command is persisted once every time it is executed
appendfsynceverysecPersist once per second
appendfsyncnoNon persistence

4. Summary

4.1RDB

advantage
  • RDB is a very compact file, which saves the data set of Redis at a certain point in time. This file is ideal for backup
  • RDB recovers large datasets faster than AOF (because its files are smaller than AOF)
  • RDB performs better than AOF
shortcoming
  • The persistence of RDB is not timely (certain time interval), and data loss may occur
  • During RDB persistence, if the file is too large, the server may be blocked. Stop the client request

4.2AOF

advantage
  • The persistence of AOF is more durable (it can be saved every second or every operation)
  • The AOF file orderly stores all writes to the database. These writes are saved in the format of Redis protocol. Therefore, the contents of the AOF file are very easy to read and analyze.
  • AOF is an incremental operation
shortcoming
  • For the same dataset, the volume of AOF file is usually larger than that of RDB file
  • Depending on the fsync policy used, AOF may be slower than RDB

4.3 selection

  • If you care about your data very much, but can still withstand data loss within a few minutes, choose RDB persistence.
  • If you have high requirements for data integrity, select AOF
  • Chapter IV - Jedis (key)

Case - a quick start to Jedis

1. Objectives

  • Master what Jedis

2. Path

  1. Introduction to jedis

  2. Introduction to Jedis

3. Explanation

3.1 introduction to jedis

Redis not only uses commands to operate, but now basically mainstream languages have client support, such as Java, C, c#, C + +, php, Node.js, Go, etc. Some Java clients are listed on the official website, including jedis, Redisson, Jredis, JDBC redis, etc. jedis and Redisson are officially recommended. Jedis is used most in enterprises, and jedis is also hosted on github

To put it bluntly, Jedis is the client (Toolkit) that uses Java to operate Redis

Address: https://github.com/xetorthio/jedis .

Document address: http://xetorthio.github.io/jedis/

methodexplain
new Jedis(host, port)Create a jedis object. The parameter host is the redis server address and the parameter port is the redis service port
set(key,value)Set string type data
get(key)Get string type data
hset(key,field,value)Set hash type data
hget(key,field)Get data of hash type
lpush(key,values)Set data for list type
lpop(key)Pop up stack on the left side of the list
rpop(key)Pop up stack on the right side of the list
sadd(String key, String... members)Set data of type set
zrange(String key, long start, long end)Gets a list of elements in a range
del(key)Delete key

3.2 introduction to jedis

Requirement: add (modify), delete and query Redis using java code

Steps:

  1. Import jar
  2. Create Jedis object
  3. Use method operation
  4. close resource
  • basic operation
@Test
public void test01(){
    //1. Create a connection to the server
    Jedis jedis = new Jedis("localhost",6379);
    //2. Call the method of jedis object to operate redis database: the method name to be called is the same as the command of redis operation
    jedis.set("user:password","123");
    //3. Close the connection
    jedis.close();
}

@Test
public void test02(){
    //Target: get the value of user:nickname from the redis server
    //1. Create a connection to the server
    Jedis jedis = new Jedis("localhost",6379);
    //2. Call get(key)
    String nickname = jedis.get("user:nickname");
    System.out.println(nickname);
    jedis.close();
}

@Test
public void test03(){
    //1. Create a connection to the server
    Jedis jedis = new Jedis("localhost",6379);
    jedis.setex("user:email",20,"123456@qq.com");
    jedis.close();
}

4. Summary

  1. Jedis: java Redis client, Toolkit
  2. Use steps
    • Import jar
    • Create jedis object
    • Call method
    • Release resources

Knowledge points - Jedis advanced

1. Objectives

  • Master the use of Jedis connection pool

2. Path

  1. Introduction to jedis connection pool
  2. Use of jedis connection pool
  3. Extraction of tool classes

3. Explanation

3.1 basic concept of jedis connection pool

The creation and destruction of jedis connection resources consume program performance, so jedis provides us with jedis pooling technology. When jedis pool is created, some connection resources are initialized and stored in the connection pool. When using jedis connection resources, it is not necessary to create them, but to obtain a resource from the connection pool for redis operation. After use, it is not necessary to destroy the jedis connection resources, Instead, the resource is returned to the connection pool for use by other requests.

3.2 use of jedis connection pool

Requirement: get jedis from jedis connection pool

Steps:

  1. Create JedisPool configuration object
  2. Create JedisPool object
  3. Get jedis from JedisPool
  4. Operating Redis
  5. Release resources
  • Basic use
@Test
public void test04(){
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    jedisPoolConfig.setMaxTotal(30);
    jedisPoolConfig.setMaxIdle(20);
    jedisPoolConfig.setMaxWaitMillis(3000);
    //Using jedis connection pool
    JedisPool jedisPool = new JedisPool(jedisPoolConfig,"localhost",6379);

    //Get connection from connection pool
    Jedis jedis = jedisPool.getResource();

    //Method calling jedis
    String nickname = jedis.get("user:nickname");
    System.out.println(nickname);

    //Return connections back to the connection pool
    jedis.close();
}

3.3 jedis tool class extraction

Purpose: 1. Ensure that there is only one connection pool. 2. Simplify the code for obtaining jedis objects

Steps:

  1. Create jedis.properties configuration file
  2. Create JedisUtils class
  3. Define the JedisPool, read the configuration file in the static code block, and initialize the JedisPool
  4. Create a getJedis() method to get Jedis from JedisPool
  5. Create close() method

Configuration file jedisconfig.properties

jedis.maxTotal=30
jedis.maxIdle=20
jedis.maxWaitMillis=3000
jedis.host=localhost
jedis.port=6379

JedisUtil tool class

package com.itheima.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ResourceBundle;

/**
 * Package name: com.weijisheng.utils
 * @author Leevi
 * Date: November 29, 2021 
 * To use jedis:
 * 1. Copy jar package
 * 2. Copy profile
 * 3. Copy tool class
 */
public class JedisUtil {
    private static JedisPool jedisPool;
    static {
        //Read the jedisconfig.properties configuration file
        ResourceBundle resourceBundle = ResourceBundle.getBundle("jedisconfig");
        Integer maxTotal = Integer.valueOf(resourceBundle.getString("jedis.maxTotal"));
        Integer maxIdle = Integer.valueOf(resourceBundle.getString("jedis.maxIdle"));
        Integer maxWaitMillis = Integer.valueOf(resourceBundle.getString("jedis.maxWaitMillis"));
        String host = resourceBundle.getString("jedis.host");
        Integer port = Integer.valueOf(resourceBundle.getString("jedis.port"));
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        //Using jedis connection pool
        jedisPool = new JedisPool(jedisPoolConfig,host,port);
    }

    /**
     * Get connection from connection pool
     * @return
     */
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}

4. Summary

  1. Purpose of using JedisPool: to reuse jedis

Case - using Redis to optimize the display of provinces

1. Demand

Visit the index.html page and load the list of provinces with ajax request (response json)

  • Get it from Redis first
    • Return directly if you have
    • Not obtained from Mysql and saved to Redis

2. Analysis

2.1 get directly from MySQL

  1. Create database and web project (page, jar, tool class, configuration file)
  2. Create a vue instance in the created hook function
axios.get('province').then(function(response){
	//Get data assignment, bind
})
  1. Create ProvinceServlet
//1. Call the service to obtain list < province > list
//2. Turn list into json response
  1. Create ProvinceService
public List<Province> findAll(){
	//Call Dao
}
  1. Create ProvinceDao

2.2 optimization ideas

  1. Get it from Redis first
    • If yes, return directly
    • If not, get it from Mysql and save it to Redis

3. Code implementation

3.1 preparation

  • database
CREATE TABLE `province` (
  `pid` int NOT NULL AUTO_INCREMENT,
  `pname` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

INSERT INTO `province` VALUES ('1', 'Guangdong');
INSERT INTO `province` VALUES ('2', 'Hubei');
INSERT INTO `province` VALUES ('3', 'Hunan');
INSERT INTO `province` VALUES ('4', 'Sichuan');
INSERT INTO `province` VALUES ('5', 'Shandong');
INSERT INTO `province` VALUES ('6', 'Shanxi');
INSERT INTO `province` VALUES ('7', 'Guangxi');
  • Create project (web)
  • Import jar package, import configuration file, import tool class, import page
  • Province.java
public class Province implements Serializable {
    private Integer pid;
    private String pname;

    @Override
    public String toString() {
        return "Province{" +
                "pid=" + pid +
                ", pname='" + pname + '\'' +
                '}';
    }

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }
}

3.2 code implementation

  • page
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Province display page</title>
    <script src="js/axios-0.18.0.js"></script>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        <select>
            <option>Please select a province</option>
            <option v-for="(province,index) in provinceList" :value="province.pid" v-html="province.pname"></option>
        </select>
    </div>
    <script>
        var vue = new Vue({
           el:"#app",
           data:{
               provinceList:[]
           },
           methods:{
               findAll(){
                   //Send asynchronous request to get all province information
                    axios.get("province?action=findAll").then(response=>{
                        this.provinceList = response.data.data
                    })
               }
           },
            created(){
               this.findAll()
            }
        });
    </script>
</body>
</html>
  • ProvinceServlet
@WebServlet("/province")
public class ProvinceServlet extends BaseServlet {
    private ProvinceService provinceService = new ProvinceService();
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultBean resultBean = new ResultBean(true);
        try {
            //Call the method of the business layer to query the information of all provinces
            List<Province> provinceList = provinceService.findAll();
            //Encapsulate the response data into a ResultBean object
            resultBean.setData(provinceList);
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setFlag(false);
            resultBean.setErrorMsg("Failed to query Province");
        }

        //Convert the resultBean object into a json string and output it to the client
        JsonUtils.printResult(response,resultBean);
    }
}
  • ProvinceService
/**
 *
 * Before optimization: the business layer directly drops the dao layer to query the mysql database
 *
 * After optimization:
 * 1. Query province information from redis
 * 2. If the query fails, call the dao layer method to query the mysql database and store the queried data in redis
 * 3. If the query is found, the data in redis will be used directly
 */
public class ProvinceService {
    private ProvinceDao provinceDao = new ProvinceDao();
    public List<Province> findAll() throws Exception {
        //1. Query province information from redis
        Jedis jedis = JedisUtil.getJedis();
        String jsonStr = jedis.get("province:list");

        //2. Judge whether jsonStr is null
        if (jsonStr == null) {
            //Description: no province information is stored in redis
            //Call dao layer method to query Province Information
            List<Province> provinceList = provinceDao.findAll();
            //Convert provinceList to jsonStr
            jsonStr = JSON.toJSONString(provinceList);
            //Store jsonStr in redis
            jedis.set("province:list",jsonStr);
        }

        //3. Convert jsonStr to list < province >
        List<Province> list = JSON.parseArray(jsonStr, Province.class);

        jedis.close();
        return list;
    }
}
  • ProvinceDao
package com.weijisheng.dao;

import com.weijisheng.pojo.Province;
import com.weijisheng.utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

/**
 * @author weijisheng
 * @create 2021-11-29 14:53
 */
public class ProviceDao {
    public List<Province> findAll() throws SQLException {
        DataSource dataSource = DruidUtil.getDataSource();
        QueryRunner queryRunner = new QueryRunner(dataSource);
        List<Province> query = queryRunner.query("select *from province", new BeanListHandler<>(Province.class));
        return query;
    }
}

4. Summary

  1. optimization
    • Get it from Redis first
      • Yes, return directly
      • No. get it from Mysql and save it to Redis

Keywords: Redis

Added by frost on Tue, 30 Nov 2021 00:26:46 +0200