Python - redis module - the way forward - Day07

Posted by angelac on Fri, 12 Nov 2021 23:44:35 +0100

Introduction to redis

1. Redis is an open source (BSD license) memory data structure store used as a database, cache, and message agent.
2. It supports data structures such as strings, hashes, lists, collections, sorted sets with range queries, bitmaps, superlogs, and geospatial indexes with radius queries.
3. Redis has built-in replication, Lua scripting, LRU expulsion, transactional and varying levels of disk persistence, and provides high availability and Redis Cluster automatic partitioning through Redis Sentinel.

redis definition

1. redis is a key-value storage system. Similar to Momcached, it supports storing relatively more value types, including string (string), list (list), set (set), zset(sorted set -- ordered set), and hash (hash type).
2. These data types support push/pop, add/remove, intersection Union and difference, and richer operations, all of which are atomic.
3. On this basis, redis supports sorting in different ways. Like memcached, data is cached in memory for efficiency.
4. The difference is that redis periodically writes updated data to disk or modifications to appended log files, and on this basis, master-slave synchronization is achieved.

redis data model

The periphery of Redis consists of a dictionary of key and value mappings. And other non Relational Database The main difference is that the type of value in Redis is not limited to strings, but also supports the following Abstract data type:

  • String List
  • Unordered and non-repeating set of strings
  • Ordered non-repeating set of strings
  • Keys and values are hash tables of strings, and the type of value determines the operations supported by the value itself. Redis supports advanced servers such as different disordered, ordered lists, intersections, unions between disordered, ordered collections Atomic Operation.

What are the benefits of using Redis?

1. Fast because data exists in memory, similar to HashMap, HashMap has the advantage that the time complexity of both finding and manipulating is O(1)

2. Support for rich data types, string, list, set, sorted set, hash

3. Supports transactions and operations are all atomic, so-called atomicity means that changes to data are either made entirely or not made entirely

4. Rich features: Can be used for caching, messaging, set expiration time by key, will automatically delete after expiration

Code example:

import redis

redis_info = {
    "host": "110.40.129.50",
    "password": "REDIS_123456!",
    "port": 6380,
    "db": 10
}


# Connect redis to add decode_directly when connecting Responses=True, so that the str type, not the byte type, is input directly
r = redis.Redis(**redis_info, decode_responses=True)

# string character exchange operation
r.set("error_count.18600597534", 5)  # Add data
print(r.get("error_count.18600597534"))  # get data
print(r.ttl("error_count.18600597534"))  # View expiration time
print(r.type("error_count.18600597534"))  # View the type of key
print("exists", r.exists("error_count.18600597534"))  # Check if the key exists, return 1 if it exists

# If an additional parameter is added, it is equivalent to setting an expiration time and expiring directly after expiration
r.set("token_count.18600597534", "afksjkfasdfhaksdhfasdfhafd", 50)
print(r.ttl("token_count.18600597534"))

print(word.center(30, "*"))

# hash
r.hset("class1", "xiaohong", '{"id":1,"age":20}')
r.hset("class2", "lilei", '{"id":1,"age":30}')
print(r.hget("class1", "xiaohong"))  # Remove the specified
print(r.hgetall("class1"))  # Take out all
# r.delete("class1", "xiaohong") # Delete executed key
r.expire("class1", 500)  # Set key expiration time for execution

print(r.hexists("class1", "xiaohong"))  # Executed small key exists
print(r.hkeys("class1"))  # Gets if all the small key s under hash exist
print(r.hvals("class1"))  # Get all the value s of hash shrimp Mina

stus = {"zhangsan": "sdad", "lisi": "adsjfajf", "zhouwu": "asdkfhadf"}
# r.hmset("class1", stus)  # Batch setup
r.hset("class1", mapping=stus)  # Batch Set value

# Used in redis: is equivalent to a folder, when added wants to be displayed as a folder
r.set("user:token:zhangdan", '{"age":12,"id":1}')

print(word.center(30, "*"))

# list
r.lpush("student", "lixaing")  # Add elements from the beginning, if this key does not exist a new one will be created
# r.delete("student")  # Delete key
r.lpushx("student", "zhangdan")  # Synchronize elements from list, do not create a new key if it does not exist
print(r.lrange("student", 0, -1))  # Gets the subscript element of a specified interval
print(r.lindex("student", 0))  # Gets the element of the specified subscript
print(r.llen("student"))  # Get the length of the list

# Add element at specified location, passing key, location (before/after), which parameter, actual parameter
print(r.linsert("student", "BEFORE", "xiaobai", "DAHUA"))
print(r.linsert("student", "AFTER", "xiaobai", "DAHUA"))

r.lset("student", 0, "Zhulixiang")  # Modify elements that execute Subscripts
print(r.lpop("student"))  # Delete the element at the end
r.lrem("students", 1, "xiaohei")  # Delete the specified element, pass 0, delete all

print(word.center(30, "*"))

# set
r.sadd("stu2", "xiaobai", "xiaohei", "zhangdan")  # Add to
r.sadd("stu3", "xiaobai", "xiaohei1", "zhangdan2")  # Add to
print(r.smembers("stu2"))  # Returns all elements of this collection
print(r.spop("stu2"))  # Randomly delete an element
print(r.sismember("stu2", "xiaosan"))  # Determine if an element is in this set
print(r.scard("stu2"))  # Returns how many elements are in the collection
print(r.sinter("stu2", "stu3"))  # Returns the intersection of two sets

# You can also use the redis command to connect remotely
# ./redis-cli -p 6380 -a 'REDIS13456!' -h '110.233.33.33'

Topics: Python Database Redis