Getting started with Redis

Keywords: Database Redis


Brief introduction to Redis

redis is a nosql database
nosql: not only sql, that is, a non relational database

Why learn nosql

Memory storage is 100000 times faster than disk reading of traditional relational database
The bandwidth of memory is also much higher than that of disk

Mainstream nosql database

Advantages of Redis

It provides rich data types and makes no difference in data storage. However, compared with memcache, it does not need to obtain all the data before parsing

Redis application scenario

Core: store data that does not change frequently and is not afraid of loss
1. Cache
2. Task queue (basically not used)
3. Data expiration processing (completed by using the expire command of redis)
4. session isolation of distributed cluster architecture
5. List of online friends in chat room
6. Ranking list (completed by using the sorted set score related commands of redis)
7. Access statistics (using commands such as incr calculation of redis)

Redis key naming specification

1. The length of the key is not longer than 1024 bytes (1m), and a kv pair can store 512mb at most
2. A key can be grouped with a colon

For example, project name: module name: key name

set projectA:moduleA:key1  testvalue
set projectA:moduleB:key1  testvalue
set projectB:moduleA:key1  testvalue
set projectB:moduleB:key1  testvalue

Client display style

Redis data type

Usage scenario:
1. Cache
2. Self increasing id
3. Counter

sorted set

Redis command

string type command

> set name wwl
> get name

hash type command

hset and hget> hset person id 1
(integer) 1> hset person name wwl
(integer) 1> hset person age 33
(integer) 1> hget person id
"1"> hget person name
"wwl"> hget person age

hmset and hmget> hmset user id 1 username hugo password 666
OK> hmget user id username password
1) "1"
2) "hugo"
3) "666"

Gets the length (number) of the field in the hash table> hlen user
(integer) 3

Delete one or more fields in the hash table> hdel user username password
(integer) 2

Delete the entire hash object> del user
(integer) 1> keys *
1) "person"

Gets all fields and values in the specified hash table> hgetall person
1) "id"
2) "1"
3) "name"
4) "wwl"
5) "age"
6) "33"

Get all fields in the hash table / get all values in the hash table> hkeys person
1) "id"
2) "name"
3) "age"> HVALS person
1) "1"
2) "wwl"
3) "33"

Examples of application scenarios: for example, store commodity information [commodity id, commodity name, commodity price]> hmset product product_id 1 product_name Iphone product_price 10000
OK> hmget product product_id product_name product_price
1) "1"
2) "Iphone"
3) "10000"

list type command

Introduction to list type storage structure

The underlying storage structure of the list data type in redis is a two-way linked list

Use of list command

Application scenario: sequence related operations, such as caching user comments

lpush is the same as lpop(rpush and rpop). The pop operation is to get and delete the value> lpush pipe a b c
(integer) 3> lpop pipe
"c"> lpop pipe
"b"> lpop pipe

Returns the number of elements in the list corresponding to the specified key> llen pipe
(integer) 0

Get elements in the list by index> rpush pipe a b c
(integer) 3> lindex pipe 0

Inserts an element before or after an element in the list> linsert pipe before a xxoo
(integer) 4> lindex pipe  0

Note: redis supports forward and reverse indexing, that is, - 1 represents the penultimate position

set type command

1. Disorder
2. Unique
3. Intersection, union and difference operation
Application scenario
1. Voting records
2. Common friends (intersection), classification labels, etc
3. Possible acquaintances (difference set)

Command of type sorted set

General commands of Redis

Redis multi database

Publish and subscribe to Redis

Redis persistence mechanism


redis data is stored in memory, and the data in memory is lost after power failure, so it needs to be persisted
There are two persistence methods in redis

1. RDB (redis database): by default, the data in redis memory is snapshot at regular intervals and stored in dump.rdb file on disk
2. AOF (append only file): records the instruction set of each operation

Advantages and disadvantages of RDB:

Small storage space
RDB is easy to cause data loss, such as sudden power failure before taking a snapshot, and the data has not been persisted to the disk
It is not convenient for database reconstruction, because only the results are recorded and there is no way to rollback
AOF advantages and disadvantages
1. Data is not easy to lose
2. The change process of database data can be recorded to facilitate database reconstruction and rollback
The files storing instruction sets and will be larger and larger

Persistent mode configuration



 Document address:

Basic use

import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

public class Demo01$Jedis {

    public static void main(String[] args) {

        Jedis jedis = new Jedis("", 6379);
        // Get the specified key
        String name = jedis.get("name");
        // Set a hash key to the redis database
        Map<String, String> fieldsMap = new HashMap<>();
        fieldsMap.put("id", "666");
        fieldsMap.put("name", "hugo");
        fieldsMap.put("age", "33");
        jedis.hmset("person", fieldsMap);

        // Release connection


Encapsulation of Jedis connection pool

Tool class encapsulation

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

import java.util.ResourceBundle;

 * @author Wei Wenlong
public class JedisUtils {

    static JedisPool jedisPool;

    static {
        ResourceBundle jedisConfig = ResourceBundle.getBundle("JedisConfig");

        Integer maxTotal = Integer.valueOf(jedisConfig.getString("jedis.MaxTotal"));
        Integer maxIdle = Integer.valueOf(jedisConfig.getString("jedis.MaxIdle"));
        Integer maxWaitMillis = Integer.valueOf(jedisConfig.getString("jedis.MaxWaitMillis"));
        Integer minIdle = Integer.valueOf(jedisConfig.getString("jedis.MinIdle"));
        String host = jedisConfig.getString("jedis.hsot");
        Integer port = Integer.valueOf(jedisConfig.getString("jedis.port"));

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();


        jedisPool = new JedisPool(jedisPoolConfig, host, port);

    public static Jedis getJedis() {
        return jedisPool.getResource();


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

public class Demo03$JedisPoolWithUtils {

    public static void main(String[] args) {
        Jedis jedis = JedisUtils.getJedis();
        String name = jedis.get("name");

Posted by PHPsites on Tue, 12 Oct 2021 15:19:30 -0700