redis entry to mastery - basic data type String

1, String

String is the most basic type of redis. A key corresponds to a value. String type can contain any data, including ordinary text data, pictures, video, audio, compressed files, etc.
String type is the most basic data type of redis. The maximum string value in a redis is 512M.

1.1 SET: set value for string

1.1.1 command format

SET key value [EX seconds] [PX milliseconds] [NX|XX]

SET the value of the key. If the key already has a value, SET overwrites the old value and ignores the type.
For a key with time to live (TTL), when the SET command is successfully executed on the key, the original TTL of the key will be cleared.

1.1.2 optional parameters

  • EX second: set the expiration time of the key to second seconds. The effect of SET key value EX second is equivalent to that of set key second value.
  • PX millisecond: set the expiration time of the key to millisecond. The SET key value PX millisecond effect is equivalent to PSETEX key millisecond value.
  • Nx: set the key only when the key does not exist. SET key value NX effect is equivalent to SETNX key value.
  • 20: Set the key only when it already exists.

1.1.3 return value

The SET command returns OK if the setting is successful, and nil if the setting fails

1.1.4 application examples

// Set key
> set name "zhangsan"
OK
> get name
zhangsan

// Set the existing key
> set name "lisi"
OK
> get name
lisi

// Set expiration time seconds
> set expire "hello"EX 10000
ERR unknown command `set expire "hello"ex 10000`, with args beginning with: 
> set expire "hello" EX 10000
OK
> ttl expire
9993
> ttl expire
9992
> get expire
hello

// Set expiration time in milliseconds
> set expirepx "hello" PX 10000
OK
> pttl expirepx
3000
> pttl expirepx
1172
> get expirepx
null

// NX
> set noexists value NX
OK
> set noexists value2 NX
null
> get noexists
value

1.1.5 complexity

O(1)

1.2 Get: get the value of string

1.2.1 command format

GET key

Gets the value of the string associated with the key

1.2.2 return value

Returns the string associated with the key. If the key does not exist, it returns nil. If the value stored by the key is not of string type, it returns an error.

1.2.3 complexity

O(1)

1.3 GETSET: get the old value and set the new value

1.3.1 command format

GETSET key value

Set the value of the given key to value and return the old value.
An error is returned when the key does not exist

1.3.2 return value

Returns the old value and an error when the key does not exist.

1.3.3 complexity

O(1)

1.3.4 application examples

// No old value, return nil
> GETSET db mongodb    
(nil)
> GET db
"mongodb"
// Return old value mongodb
> GETSET db redis      
"mongodb"
> GET db
"redis"

1.4 MSET: set multiple string key value pairs at one time

1.4.1 command format

MSET key value [key value ...]

Set multiple key value pairs at the same time. If a key already exists, mset will overwrite the old value with the new value.
MSET is an atomic operation. All given key s will be set at the same time.

1.4.2 return value

Always return OK, MSET will not fail

1.4.3 complexity

O(N),N is the number of string keys given by the user.

1.4.4 application examples

> MSET id "10086" name "zhangsan"
OK

> MGET id name
1) 10086
2) zhangsan

// Example of MSET overwriting old values
> SET id "10086"
OK

> MSET id "1008611"
OK

> GET id
1008611

1.5 MSETNX: set values for multiple strings at one time only when the key does not exist

1.5.1 command format

MSETNX key value [key value ...]

Set multiple key value pairs at the same time. If a key already exists, msetnx will discard all key value pair setting operations.

1.5.2 return value

Returns 1 on success and 0 on failure

1.5.3 complexity

O(N),N is the number of string keys given by the user.

1.5.4 application examples

> msetnx id 10086 name zhangsan
1
> MGET id name
10086
zhangsan
> msetnx id 1008611 name lisi sex nan
0
> mget id name sex
10086
zhangsan
null

1.6 MGET: get the values of multiple string keys at one time

1.6.1 command format

Gets the value corresponding to multiple string keys.

1.6.2 return value

The value of all given key s.

1.6.3 complexity

O (n), n is the number of given key s.

1.7 STRLEN: gets the byte length of the string

1.7.1 command format

STRLEN key

Returns the length of the string stored by the key. When the key is not a string, an error is returned.

1.7.2 return value

Returns the length of the string stored by the key. When the key is not a string, an error is returned.

1.7.3 complexity

O(1)

1.7.4 application examples

> set key "hello world"
OK
> strlen key
11
//Nonexistent key
> strlen noexist
0

1.8 GETRANGE: get the contents of the specified range of string values

A string consists of consecutive bytes, so each byte has a corresponding index. redis provides index operation commands for strings, allowing users to process through positive / negative indexes

  • The forward index takes 0 as the first byte, increasing from the beginning to the end.
  • The negative index takes - 1 as the last byte and decrements to the beginning.
    For example, the index of the string hello world is shown in the figure below

1.8.1 command format

GETRANGE key start end

With the GETRANGE command, the user can obtain the string value from the start index to the end index. The offset of this command is the closed interval index range, that is, the start index and end index are also included in the returned content of the command.

1.8.2 return value

Intercepted substring.

1.8.3 complexity

O(N), N is the length of the string to be returned.

1.8.4 application examples

> set key "hello redis!"
OK
// Intercepting strings of 0-4
> getrange key 0 4
hello
// Acquisition failed
> getrange key -1 -5

// Negative index
> getrange key -3 -1
is!
// From first to last
> getrange key 0 -1
hello redis!
// Beyond return ignore
> getrange key 0 100
hello redis!

1.10 SETRANGE: set the specified range of string value

1.10.1 command format

SETRANGE key offset value

Starting from offset, use value to overwrite the original key.

  • If the key does not exist, it will be treated as an empty string.
  • If the original string of key is smaller than the offset, the space between the original character and the offset will be filled with zero bytes ('\ x00').
  • The maximum offset is 2 ^ 29-1 (536870911), because the size of the redis string is limited to 512M.
  • When generating a very long string, redis needs to allocate memory space, so sometimes the server will be blocked.

1.10.2 return value

The length of the string after being modified by SETRANGE.

1.10.3 complexity

For small strings, the average complexity is O(1), otherwise it is O (m), and M is the length of value.

1.10.4 application examples

> set key "hello world"
OK
> setrange key 6 redis
11
> get key
hello redis
// setrange the nonexistent key
> setrange noexist 5 'redis'
10
> get noexist
redis

1.11 APPEND: add new content to the end of the value

1.11.1 command format

APPEND key value

If the key already exists and is a string, append value to the end of the original value of the key.

1.11.2 return value

Returns the length of the string of key after value is appended.

1.11.3 complexity

Average O(1)

1.11.4 application examples

···

exists key
0
//append a nonexistent key, which is equivalent to set
append key "hello"
5
//append existing key s
append key " world"
11
get key
hello world
···

1.12 INCRBY, DECRBY, INCR, DECR: add and subtract integers

In redis, if the user stores a value in the string key, redis will detect the value. If the value can be interpreted as one of the following two types, redis will treat the value as a number:

  • Integer type: it can use the long long int type of C to store integers. In most systems, this type stores 64 bit signed integers.
  • Floating point type: floating point numbers that can be stored using the long double type of C. in most systems, this type stores 128 bit signed floating point numbers.

When the string key can be interpreted as an integer, you can use the INCRBY and DECRBY commands to add and subtract integers.

1.12.1 command format

INCRBY key increment
DECRBY key decrement
INCR key
DECR key

If the type corresponding to the key is not an integer, an error will be returned.

  • INCRBY: increment the value stored by the key. If the key does not exist, the key will be initialized to 0 and then INCRBY will be executed.
  • DECRBY: subtract the decrement from the value stored by the key. If the key does not exist, the key will be initialized to 0 and then DECRBY will be executed.
  • INCR: add 1 to the value stored by the key. If the key does not exist, the key will be initialized to 0 and then execute INCR.
  • DECR: subtract 1 from the stored value of the key. If the key does not exist, the key will be initialized to 0 before DECR is executed.
    The time complexity is O(1)

1.13 INCRBYFLOAT: add floating point numbers

1.13.1 command format

INCRBYFLOAT key increment

INCRBYFLOAT can be used for both floating-point numbers and integers.
When using INCRBYFLOAT to process floating-point numbers, only 17 digits after the calculated decimal point will be reserved at most, and the excess will be truncated.
Time complexity bit O(1)

1.14

2, Apply

2.1 caching

Redis is a memory database, so the speed will be much faster. Moreover, the string key of redis can store not only text data but also binary data, so it can be used to cache popular pictures, so as to improve the speed of popular pictures.

package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"io"
	"os"
)

func main() {
	rdb := redis.NewClient(&redis.Options{
		Addr: "127.0.0.1:6379",
		DB:   0,
	})
	ctx := context.Background()
	rdb.FlushDB(ctx)
	file, err := os.Open("D://workspace//myOpenSource//go-example//go-redis//01-string//cache//redis-logo.jpg")
	defer file.Close()
	if err != nil {
		panic(err)
	}
	data, err := io.ReadAll(file)
	if err != nil {
		panic(err)
	}
	rdb.Set(ctx, "redis-logo.jpg", data, -1)
	fmt.Println(rdb.Get(ctx, "redis-logo.jpg"))
}

2.2 lock

Lock is a synchronization mechanism used to ensure that a resource can only be used by one process at any time. If other processes want to use the same resource, they must wait until the resource process in use gives up using all resources.
Locks usually implement two operations: acquire and release:

  • Acquire: used to obtain exclusive use rights of resources. At most one process can obtain a lock at any time. We call the process that successfully obtains the lock the lock holder. When the lock is already held, all attempts to acquire the lock will fail.
  • Release: used to give up the exclusive use right of resources. It is generally called by the lock holder. After the lock is released, other processes can try to acquire the lock again.
    The following code shows the GO implementation lock
package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
)

type Lock struct {
	ctx context.Context
	rdb *redis.Client
	key string
}

func New(key string) *Lock {
	lock := &Lock{
		ctx: context.Background(),
		rdb: redis.NewClient(&redis.Options{
			Addr: "127.0.0.1:6379",
			DB:   0,
		}),
		key: key,
	}

	return lock

}

func (self *Lock) acquire() bool {
	ok, _ := self.rdb.SetNX(self.ctx, self.key, "lock", -1).Result()
	return ok
}

func (self *Lock) release() bool {
	res, err := self.rdb.Del(self.ctx, self.key).Result()
	return err == nil && res == 1
}

func main() {
	l := New("lock")
	if l.acquire() {
		fmt.Println("Get success")
	} else {
		fmt.Println("Acquisition failed")
	}
	if l.acquire() {
		fmt.Println("Get success")
	} else {
		fmt.Println("Acquisition failed")
	}
	if l.release() {
		fmt.Println("Release successful")
	} else {
		fmt.Println("Release failed")
	}
	if l.acquire() {
		fmt.Println("Get success")
	} else {
		fmt.Println("Acquisition failed")
	}
}

The results are as follows:

Get success
 Acquisition failed
 Release successful
 Get success

2.3 storing articles

When building a blog program, we need to store the following information:

  • User information: user's name, account number, password, registration time and other information.
  • Blog information: when users write a new article to, they need to store the title, content, author, publishing time and other information of the article, and take out these information when users read the article.

Technical reference

  1. C/C++Linux server development / background Architect: https://ke.qq.com/course/417774?flowToken=1041607
  2. redis user manual
  3. http://doc.redisfans.com/string/index.html

Keywords: Redis Cache nosql

Added by jervo on Mon, 17 Jan 2022 01:17:29 +0200