Features and functions of some database and cache serversP4

The name of the type Data storage options Types of queries Additional features
Redis Non-relational databases that use in-memory storage String, list, hash table, set, ordered set Each data type has its own proprietary commands, as well as bulk operation and partial transaction support Publish and subscribe, master/ Slave Replication
memcached Use an in-memory cache of key values Mapping between key values Add, delete, change, check and several other commands Multi-threaded server for improved performance
MySQL Relational database Each database can contain multiple tables, and each table can contain multiple rows; Can handle multiple table attempts (views); Support for spatial and third-party extension Add, delete, change, search, function, stored procedure ACID properties (need to use InnoDB), master/master replication and master/master replication
PostgreSQL Relational database Each database can contain multiple tables, and each table can contain multiple rows; Can handle multiple table attempts; Support for spatial and third-party extensions; Customizable types are supported Add, delete, modify, search, built-in functions, custom stored procedures ACID properties, master/slave replication, and multi-master replication supported by a third party
MongoDB Non-relational document storage using on-disk storage Each database can contain multiple tables, and each table can contain multiple BSON documents without schema (schema-less). Add and delete Supports Map-Reduce operations, primary/secondary replication, sharding, and spatial index.

Persistent modeP4

  • Redis Database (RDB) : data is persisted to disks in the form of snapshots
  • AOF(Append only File) : records each operation in the form of logs, and records all commands executed by Redis (read operations are not recorded). Files can be appended but cannot be modified. When Redis starts, it reads the AOF configuration file to reconstruct data

5 structures of RedisP6

Structure type Structure to store values Structure literacy
STRING It can be a string, integer, or floating point Perform an operation on the entire string or part of a string; Perform increment or Decrement for integers and floating-point numbers
LIST A linked list in which each node contains a string Push or pop elements from both ends of the list; Trim the list according to the offset; Read single or multiple elements; Find or remove elements by value
HASH An unordered hash table containing key-value pairs Add, get, and remove single key-value pairs; Gets all key-value pairs
SET An unordered collection that contains strings, and each contained string is unique and distinct Add, get, and remove individual elements Checks if an element exists in the collection; Calculate intersection, union and difference sets; Retrieves elements randomly from the collection
ZSET (Ordered set) An ordered mapping between a string member and a floating-point score. The order of elements is determined by the size of the score Add, get, and remove individual elements Retrieves elements based on a range of points or members
STRING base commandP8

STRING stores key-value pairs, which can be either strings or numeric values (values can be incremented or decrement)

package main

import (
    "fmt"
    "github.com/gomodule/redigo/redis"
    "time"
)

func main(a) {
    // Get the connection
    conn, err := redis.Dial("tcp"."127.0.0.1:6379")
    iferr ! =nil {
        // If the connection fails, an error message is displayed and exit
        fmt.Println(err)
        return
    }

    // If the connection is successful, the shutdown is delayed
    defer conn.Close()

    executeStringCommand(conn)
}

// Execute the STRING command
func executeStringCommand(conn redis.Conn) {
    fmt.Println("--------- executeStringCommand start ---------")

    // Set the key to hello to world forever
    result, err := conn.Do("SET"."hello"."world")
    handleResult(result, err)

    TTL -> seconds, PTTL -> milliseconds
    result, err = redis.Int(conn.Do("TTL"."hello"))
    handleResult(result, err)

    // Get the value with the key hello
    result, err = redis.String(conn.Do("GET"."hello"))
    handleResult(result, err)

    // Set the key to hello with a value of world and a valid time of 1000ms (EX -> SEC, PX -> ms; Not both)
    result, err = conn.Do("SET"."hello"."world"."EX"."1")
    handleResult(result, err)

    TTL -> seconds, PTTL -> milliseconds
    result, err = redis.Int(conn.Do("PTTL"."hello"))
    handleResult(result, err)

    time.Sleep(time.Second * 2)
    TTL -> seconds, PTTL -> milliseconds
    result, err = redis.Int(conn.Do("PTTL"."hello"))
    handleResult(result, err)

    // Set the hello key to world, permanently (NX -> key does not exist, set operation; XX -> key already exists.)
    result, err = conn.Do("SET"."hello"."world!"."XX")
    handleResult(result, err)

    // Set the hello key to world, permanently (NX -> key does not exist, set operation; XX -> key already exists.)
    result, err = conn.Do("SET"."hello"."world!"."NX")
    handleResult(result, err)

    // Delete values with a key of Hello (can be used for all types)
    result, err = conn.Do("DEL"."hello")
    handleResult(result, err)

    // Get the value with the key hello
    result, err = redis.String(conn.Do("GET"."hello"))
    handleResult(result, err)

    fmt.Println("--------- executeStringCommand end ---------")}// Process the result of the redis operation
func handleResult(result interface{}, err error) {
    iferr ! =nil {
        fmt.Println("ERROR: ", err)
        return
    }
    fmt.Println(result)
}
Copy the code
LIST Basic commandsP9
// Execute the related commands of LIST
func executeListCommand(conn redis.Conn) {
    fmt.Println("--------- executeListCommand start ---------")

    // Insert values at the right end of the list
    result, err := conn.Do("RPUSH"."list"."item-1"."item-2")
    handleResult(result, err)

    // Insert values at the left end of the list
    result, err = conn.Do("LPUSH"."list"."item-3"."item-4")
    handleResult(result, err)

    // Retrieve all values in the range [1, 3] from the left end of the list (end index -1 indicates that all elements can be retrieved at the end of the list; No RRANGE command)
    result, err = redis.Strings(conn.Do("LRANGE"."list"."1"."1"))
    handleResult(result, err)

    // Get index 0 in list with left header (no RINDEX command)
    result, err = redis.String(conn.Do("LINDEX"."list"."0"))
    handleResult(result, err)

    // Pop up a value at the right end of the list
    result, err = redis.String(conn.Do("RPOP"."list"))
    handleResult(result, err)

    // Pop up a value at the left of the list
    result, err = redis.String(conn.Do("LPOP"."list"))
    handleResult(result, err)

    // Delete values with keys list (can be used for all types)
    result, err = conn.Do("DEL"."list")
    handleResult(result, err)

    // Get all the values in the list starting with the left end
    result, err = redis.Strings(conn.Do("LRANGE"."list"."0"."1"))
    handleResult(result, err)

    fmt.Println("--------- executeListCommand end ---------")}Copy the code
SET basic commandP10
// Run the SET command
func executeSetCommand(conn redis.Conn) {
    fmt.Println("--------- executeSetCommand start ---------")

    // Add values to set
    result, err := conn.Do("SADD"."set"."item-1"."item-2"."item-2"."item-3"."item-4")
    handleResult(result, err)

    // Remove the value from the set
    result, err = conn.Do("SREM"."set"."item-2"."item-3")
    handleResult(result, err)

    // Check whether a value is in the set
    result, err = redis.Bool(conn.Do("SISMEMBER"."set"."item-2"))
    handleResult(result, err)

    // Get all values of set (not recommended, large keys slow execution)
    result, err = redis.Strings(conn.Do("SMEMBERS"."set"))
    handleResult(result, err)

    // Delete values whose key is set (can be used for all types)
    result, err = conn.Do("DEL"."set")
    handleResult(result, err)

    fmt.Println("--------- executeSetCommand end ---------")}Copy the code
HASH basic commandsP11

HASH stores mappings between multiple key-value pairs, and, like STRING, stores values that can be either strings or numeric values (values can be incremented or decrement)

// Run the HASH command
func executeHashCommand(conn redis.Conn) {
    fmt.Println("--------- executeHashCommand start ---------")

    // Add a key-value pair to the hash table
    result, err := conn.Do("HSET"."hash"."key-1"."item-1")
    handleResult(result, err)

    // Add multiple key-value pairs to the hash table
    result, err = conn.Do("HMSET"."hash"."key-2"."item-2"."key-3"."item-3"."key-4"."item-4"."key-5"."item-5")
    handleResult(result, err)

    // Get the key-1 value from the hash table
    result, err = redis.String(conn.Do("HGET"."hash"."key-1"))
    handleResult(result, err)

    // Get multiple key-value pairs from the hash table (return values in the same order as the arguments passed in)
    result, err = redis.Strings(conn.Do("HMGET"."hash"."key-2"."key-1"))
    handleResult(result, err)

    // Delete key-1 from hash table (can be used for all types)
    result, err = conn.Do("HDEL"."hash"."key-1")
    handleResult(result, err)

    // Retrieve all key-value pairs from the hash table (not recommended, large keys perform slowly)
    result, err = redis.StringMap(conn.Do("HGETALL"."hash"))
    handleResult(result, err)

    // Delete values with hash keys (can be used for all types)
    result, err = conn.Do("DEL"."hash")
    handleResult(result, err)

    fmt.Println("--------- executeHashCommand end ---------")}Copy the code
ZSET basic commandP12

ZSET, like HASH, is used to store key-value pairs. The keys of a ZSET are called members, and each member is different; A value is called a score, and the score must be a floating point number. ZSET is the only Redis that can access elements by members and by points and the order in which they are arranged.

// Run the ZSET command
func executeZsetCommand(conn redis.Conn) {
    fmt.Println("--------- executeZsetCommand start ---------")

    // Add a value to the zset ordered collection
    result, err := conn.Do("ZADD"."zset"."0"."item-1"."12.34"."item-1"."12.34"."item-2"."56.78"."item-3"."56.78"."item-4"."56.78"."item-5")
    handleResult(result, err)

    // Remove the value from the zset ordered collection
    result, err = conn.Do("ZREM"."zset"."item-2"."item-3")
    handleResult(result, err)

    // Get the specified range of values in the zset ordered collection (end index -1 indicates all values from the start index to the end index)
    // Members are sorted in ascending order of score. Members with the same score are sorted in ascending order of lexicographical order
    // The WITHSCORES option returns the member with its score value in the list format: value1,score1... , valueN,scoreN
    result, err = redis.Strings(conn.Do("ZRANGE"."zset"."0"."1"."WITHSCORES"))
    handleResult(result, err)

    // Get the specified range of values in the zset ordered collection (end index -1 indicates all values from the start index to the end index)
    // Members are sorted in descending order of score. Members with the same score are sorted in descending order of lexicographical order
    // The WITHSCORES option returns the member with its score value in the list format: value1,score1... , valueN,scoreN
    result, err = redis.Strings(conn.Do("ZREVRANGE"."zset"."0"."1"."WITHSCORES"))
    handleResult(result, err)

    / / get zset an ordered set of score in the specified range min, Max value (- inf: minus infinity, + inf is infinite; The default is closed interval, and the number is preceded (to indicate the open interval).
    // Members are sorted in ascending order of score. Members with the same score are sorted in ascending order of lexicographical order
    // The WITHSCORES option returns the member with its score value in the list format: value1,score1... , valueN,scoreN
    // LIMIT offset, count, like LIMIT in SQL, specifies the number and range of results to be returned
    result, err = redis.Strings(conn.Do("ZRANGEBYSCORE"."zset"."-inf"."+inf"."WITHSCORES"))
    handleResult(result, err)

    -inf: -inf: -infinity, + INF: -infinity; The default is closed interval, and the number is preceded (to indicate the open interval).
    // Members are sorted in descending order of score. Members with the same score are sorted in descending order of lexicographical order
    // The WITHSCORES option returns the member with its score value in the list format: value1,score1... , valueN,scoreN
    // LIMIT offset, count, like LIMIT in SQL, specifies the number and range of results to be returned
    result, err = redis.Strings(conn.Do("ZREVRANGEBYSCORE"."zset"."(12.34"."-inf"."WITHSCORES"."LIMIT"."1"."1"))
    handleResult(result, err)

    // Delete values with key zset (can be used for all types)
    result, err = conn.Do("DEL"."zset")
    handleResult(result, err)

    fmt.Println("--------- executeZsetCommand end ---------")}Copy the code

thoughts

  • Slow is fast, don’t think too much. At the beginning of the first few pages I felt too basic, usually used, do not want to continue to read. On second thought, I only knew the function of part of the instructions before and did not practice them. This time, I could operate them well. In order to improve their interest, decided to use Golang to call practice, kill two birds with one stone.

This article is published on GitHub: Reading-notes/Redis-in-Action