Redis practice 01. Brief introduction of redis data structure

Man Fu Zhu Ji 2021-01-20 21:31:47
redis practice brief introduction redis


Features and functions of some database and cache servers P4

name type Data storage options Query type Additional features
Redis Use memory storage (in-memory) Non relational database character string 、 list 、 Hashtable 、 aggregate 、 Ordered set Each data type has its own commands , There are also batch operations (bulk operation) And incomplete (partial) Transaction support for Publish and subscribe , Master slave copy (master/slave replication)
memcached Use the key value cache stored in memory Mapping between key values Add, delete, change and search and several other commands Multithreaded server designed to improve performance
MySQL relational database Each database can contain multiple tables , Each table can contain multiple rows ; Can handle multiple tables (view); Support space (spatial) And third party expansion Additions and deletions 、 function 、 stored procedure Support ACID nature ( Need to use InnoDB), Master slave replication and master master replication (master/master replication)
PostgreSQL relational database Each database can contain multiple tables , Each table can contain multiple rows ; Can handle multiple tables ; Support for space and third party expansion ; Supports customizable types Additions and deletions 、 Built in functions 、 Custom stored procedures Support ACID nature , Master slave copy , Multi master replication supported by third party (multi-master replication)
MongoDB Use hard disk storage (on-disk) Non relational document storage for Each database can contain multiple tables , Each table can contain multiple none schema (schema-less) Of BSON file (Binary JSON, similar json A binary format of ) Additions and deletions Support map-reduce operation , Master slave copy , Fragmentation , Spatial index (spatial index)

Persistence mode P4

  • RDB(redis database): Persistent data to disk in the form of snapshot
  • AOF(append only file): Log each operation , take Redis All instructions executed are recorded ( Reading operation does not record ), You can only add files, but you can't modify them ,Redis Will read on startup AOF Profile refactoring data

Redis Of 5 Kinds of structure P6

Structure type The value stored by the structure Read and write ability of structure
STRING Can be a string 、 Integer or floating point Perform operations on the entire string or part of the string ; Autoincrement for integers and floating-point numbers (increment) Or self reducing (decrement)
LIST A linked list , Each node on the list contains a string Push or eject elements from both ends of the list ; Trim the linked list according to the offset (trim); Read single or multiple elements ; Find or remove elements based on values
HASH Unordered hash table containing key value pairs add to 、 obtain 、 Remove a single key value pair ; Get all key value pairs
SET Unordered collector with strings (unordered collection), And each string contained is unique 、 Different add to 、 obtain 、 Remove single element ; Check if an element exists in the collection ; Calculate the intersection 、 Combine 、 Difference set ; Get elements randomly from the collection
ZSET( Ordered set ) String members (member) And floating-point scores (score) The orderly mapping between , The order of the elements is determined by the size of the score add to 、 obtain 、 Remove single element ; According to the score range (range) Or members to get elements
STRING Basic commands P8

STRING Store key value pairs , The value can be either a string , It can also be numerical ( The numerical value supports self increasing and self decreasing )

package main
import (
"fmt"
"github.com/gomodule/redigo/redis"
"time"
)
func main() {
// Get the connection 
conn, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
// The connection fails , Print the error message , And exit 
fmt.Println(err)
return
}
// If the connection is successful , Delay execution close 
defer conn.Close()
executeStringCommand(conn)
}
// perform STRING Related commands 
func executeStringCommand(conn redis.Conn) {
fmt.Println("--------- executeStringCommand start ---------")
// Set up The key is hello The value of is world, Permanent validity 
result, err := conn.Do("SET", "hello", "world")
handleResult(result, err)
// obtain The key is hello The rest of the time (TTL -> second ,PTTL -> millisecond )
result, err = redis.Int(conn.Do("TTL", "hello"))
handleResult(result, err)
// obtain The key is hello Value 
result, err = redis.String(conn.Do("GET", "hello"))
handleResult(result, err)
// Set up The key is hello The value of is world, The effective time is 1000ms(EX -> second ,PX -> millisecond ; Do not use at the same time )
result, err = conn.Do("SET", "hello", "world", "EX", "1")
handleResult(result, err)
// obtain The key is hello The rest of the time (TTL -> second ,PTTL -> millisecond )
result, err = redis.Int(conn.Do("PTTL", "hello"))
handleResult(result, err)
time.Sleep(time.Second * 2)
// obtain The key is hello The rest of the time (TTL -> second ,PTTL -> millisecond )
result, err = redis.Int(conn.Do("PTTL", "hello"))
handleResult(result, err)
// Set up The key is hello The value of is world, Permanent validity (NX -> When the key doesn't exist , Setting operation only ;XX -> When the key already exists , Setting operation only )
result, err = conn.Do("SET", "hello", "world!", "XX")
handleResult(result, err)
// Set up The key is hello The value of is world, Permanent validity (NX -> When the key doesn't exist , Setting operation only ;XX -> When the key already exists , Setting operation only )
result, err = conn.Do("SET", "hello", "world!", "NX")
handleResult(result, err)
// Delete The key is hello Value ( Can be used for all types of )
result, err = conn.Do("DEL", "hello")
handleResult(result, err)
// obtain The key is hello Value 
result, err = redis.String(conn.Do("GET", "hello"))
handleResult(result, err)
fmt.Println("--------- executeStringCommand end ---------")
}
// Processing operations redis Result 
func handleResult(result interface{}, err error) {
if err != nil {
fmt.Println("ERROR: ", err)
return
}
fmt.Println(result)
}
LIST Basic commands P9
// perform LIST Related commands 
func executeListCommand(conn redis.Conn) {
fmt.Println("--------- executeListCommand start ---------")
// stay list List Right end Insert value 
result, err := conn.Do("RPUSH", "list", "item-1", "item-2")
handleResult(result, err)
// stay list List Left side Insert value 
result, err = conn.Do("LPUSH", "list", "item-3", "item-4")
handleResult(result, err)
// stay list In the list Take the left end as the head [1, 3] All values in range ( The end index is -1 Represents all elements that can be taken out to the end of the list ; No, RRANGE command )
result, err = redis.Strings(conn.Do("LRANGE", "list", "1", "-1"))
handleResult(result, err)
// stay list In the list Take the left end as the head Subscript to be 0( No, RINDEX command )
result, err = redis.String(conn.Do("LINDEX", "list", "0"))
handleResult(result, err)
// stay list List Right end Pop up and add a value 
result, err = redis.String(conn.Do("RPOP", "list"))
handleResult(result, err)
// stay list List Left side Pop up and add a value 
result, err = redis.String(conn.Do("LPOP", "list"))
handleResult(result, err)
// Delete The key is list Value ( Can be used for all types of )
result, err = conn.Do("DEL", "list")
handleResult(result, err)
// stay list In the list Take the left end as the header to get all the values 
result, err = redis.Strings(conn.Do("LRANGE", "list", "0", "-1"))
handleResult(result, err)
fmt.Println("--------- executeListCommand end ---------")
}
SET Basic commands P10
// perform SET Related commands
func executeSetCommand(conn redis.Conn) {
fmt.Println("--------- executeSetCommand start ---------")
// stay set Collection add value
result, err := conn.Do("SADD", "set", "item-1", "item-2", "item-2", "item-3", "item-4")
handleResult(result, err)
// from set Collection Delete value
result, err = conn.Do("SREM", "set", "item-2", "item-3")
handleResult(result, err)
// Determine whether a value is in set Collection
result, err = redis.Bool(conn.Do("SISMEMBER", "set", "item-2"))
handleResult(result, err)
// obtain set Collection All values ( It is not recommended to use , Big key Slow execution )
result, err = redis.Strings(conn.Do("SMEMBERS", "set"))
handleResult(result, err)
// Delete The key is set Value ( Can be used for all types of )
result, err = conn.Do("DEL", "set")
handleResult(result, err)
fmt.Println("--------- executeSetCommand end ---------")
}
HASH Basic commands P11

HASH The mapping between multiple key value pairs can be stored , and STRING equally , The stored value can be either a string , It can also be numerical ( The numerical value supports self increasing and self decreasing )

// perform HASH Related commands 
func executeHashCommand(conn redis.Conn) {
fmt.Println("--------- executeHashCommand start ---------")
// stay hash In the hash table Add a key value pair 
result, err := conn.Do("HSET", "hash", "key-1", "item-1")
handleResult(result, err)
// stay hash In the hash table Add multiple key value pairs 
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)
// from hash In the hash table Get key by key-1 Value 
result, err = redis.String(conn.Do("HGET", "hash", "key-1"))
handleResult(result, err)
// from hash In the hash table Get multiple key value pairs ( The order of the returned values is the same as the order of the passed in parameters )
result, err = redis.Strings(conn.Do("HMGET", "hash", "key-2", "key-1"))
handleResult(result, err)
// Delete hash The key in the hash table is key-1 Value ( Can be used for all types of )
result, err = conn.Do("HDEL", "hash", "key-1")
handleResult(result, err)
// from hash In the hash table Get all key value pairs ( It is not recommended to use , Big key Slow execution )
result, err = redis.StringMap(conn.Do("HGETALL", "hash"))
handleResult(result, err)
// Delete The key is hash Value ( Can be used for all types of )
result, err = conn.Do("DEL", "hash")
handleResult(result, err)
fmt.Println("--------- executeHashCommand end ---------")
}
ZSET Basic commands P12

ZSET and HASH equally , Both are used to store key-value pairs .ZSET The key is called a member (member), Each member is different ; The value is called the score (score), Score must be floating point .ZSET yes Redis The only element can be accessed according to members , You can also access the structure of the elements according to their points and the order in which they are arranged .

// perform ZSET Related commands 
func executeZsetCommand(conn redis.Conn) {
fmt.Println("--------- executeZsetCommand start ---------")
// stay zset In an orderly collection add value 
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)
// from zset In an orderly collection Delete value 
result, err = conn.Do("ZREM", "zset", "item-2", "item-3")
handleResult(result, err)
// obtain zset In an orderly collection The value of the specified range ( The end index is -1 Represents all values from the beginning of the index to the end )
// For the position of the members, press score Value increment ( From small to large ) Sort by , identical score The members of the value are arranged in ascending dictionary order 
// WITHSCORES Option allows the member and its score The value returns , Return to list format :value1,score1, ..., valueN,scoreN
result, err = redis.Strings(conn.Do("ZRANGE", "zset", "0", "-1", "WITHSCORES"))
handleResult(result, err)
// obtain zset In an orderly collection The value of the specified range ( The end index is -1 Represents all values from the beginning of the index to the end )
// For the position of the members, press score The value is decreasing ( From small to large ) Sort by , identical score The members of the value are arranged in descending dictionary order 
// WITHSCORES Option allows the member and its score The value returns , Return to list format :value1,score1, ..., valueN,scoreN
result, err = redis.Strings(conn.Do("ZREVRANGE", "zset", "0", "-1", "WITHSCORES"))
handleResult(result, err)
// obtain zset In an orderly collection score In the specified range min, max Value (-inf: Negative infinity ,+inf It's just infinite ; The default is closed , Add before number ( Open interval )
// For the position of the members, press score Value increment ( From small to large ) Sort by , identical score The members of the value are arranged in ascending dictionary order 
// WITHSCORES Option allows the member and its score The value returns , Return to list format :value1,score1, ..., valueN,scoreN
// LIMIT offset, count and SQL in limit equally , Specify the number and range of returned results 
result, err = redis.Strings(conn.Do("ZRANGEBYSCORE", "zset", "-inf", "+inf", "WITHSCORES"))
handleResult(result, err)
// obtain zset In an orderly collection score In the specified range max, min Value (-inf: Negative infinity ,+inf It's just infinite ; The default is closed , Add before number ( Open interval )
// For the position of the members, press score The value is decreasing ( From small to large ) Sort by , identical score The members of the value are arranged in descending dictionary order 
// WITHSCORES Option allows the member and its score The value returns , Return to list format :value1,score1, ..., valueN,scoreN
// LIMIT offset, count and SQL in limit equally , Specify the number and range of returned results 
result, err = redis.Strings(conn.Do("ZREVRANGEBYSCORE", "zset", "(12.34", "-inf", "WITHSCORES", "LIMIT", "1", "1"))
handleResult(result, err)
// Delete The key is zset Value ( Can be used for all types of )
result, err = conn.Do("DEL", "zset")
handleResult(result, err)
fmt.Println("--------- executeZsetCommand end ---------")
}

Thinking and thinking

  • Slow is fast , Don't look too high or too low . At the beginning of reading a few pages, I felt it was too basic , It's usually used , I don't want to read any more . Think about it. , Before, I only knew the function of some instructions , No practice , This time we can do a good job . In order to improve my interest , Decided to use Golang Call to practice , Kill two birds with one stone .

This article was first published on the official account : Man Fu Zhu Ji ( Click to view the original ) Open source in GitHub :reading-notes/redis-in-action


版权声明
本文为[Man Fu Zhu Ji]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210120213016987U.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云