Redis Common Operations

Keywords: Python Redis Database

Redis introduction

Redis is a fully open source, free, high-performance Key-Value database with the following characteristics:

  • Redis supports data persistence, saves data in memory to disk, and reboots can be loaded again for use.
  • Redis not only supports simple Key-Value type quantitative data, but also provides storage of list, set, zset (ordered set), hash and other data structures.
  • Redis supports backup of data, i.e. master-slave mode.

Redis Basic Operation

1. String-related operations

Method Explain parameter Explain Example
set Set value EX Setting cache time/expiration time set animal 'cat' EX 5
Setting a value using multiple fields, such as setting a user information set user:Joshua;age:24 "19950427"
get Get value get animal
Getting values through multiple fields get user:Joshua;age:24
append Adding strings append animal " Dog"
mset Adding multiple values mset user1 'Joshua' user2 'root'
mget Get multiple values mget user1 user2 animal
del delete del del animal
incr/decr Increase 1/decrease 1 Incr num decr num num num is pre-set

2. List-related operations

Method Explain Example
rpush Push one or more values to the right of the list rpush mylist Joshua
lpush Push one or more values to the left of the list lpush mylist Hello
rpop Remove the rightmost element of the list rpop mylist
lpop Remove the leftmost element of the list lpop mylist
lindex Query the value of an offset lindex mylist 0
lrange Query elements within an offset range lrange mylist 0 2
ltrim Intercept a value and delete other values ltrim mylist 0 3
blpop Extract and delete an element from the leftmost end of the non-empty list, or wait for the pop-up element to appear within seconds of timeout blpop mylist 0
brpop Extract and delete an element from the far right of the non-list, or wait for a pop-up element to appear within seconds of timeout brpop mylist 0
rpoplpush Extract and delete an element from the right end of source_list and add it to the left-most side of desc_lsit rpoplpush mylist youlist
brpoplpush Extract and delete the element from the rightmost end of the source_list in timeout seconds, add it to the leftmost side of desc_list, and wait for the element to pop up in timeout seconds if the source_list is empty brpoplpjush mylist youlist 5
lpushx Push one or more values to the left of the list when the key exists, otherwise nothing is done. lpushx itslist 0
rpushx Push one or more values to the right of the list when the key exists, otherwise do nothing.

3. Set-related operations

Method Explain Example
sadd/srem Add an element to the collection/delete an element sadd myset cat dog / srem myset cat
smembers Get all the elements of the collection smembers myset
sismember See if an element is in a collection sismember myset cat
sdiff Returns a collection that is different from other collections sdiff myset1 myset2 # Note that there is no myset1 element in myset2
sinter Returns the intersection of several sets sinter myset1 myset2
sunion Returns the union of several sets sunion myset1 myset2

4. hash operation

Method Explain Example
hset Set a hash value Hset News: 1 Title "News Title" News: 1 means News with an id of 1
hget Get a hash value hget News:1 title
hsetnx Set a hash value, but not if it exists hsetnx News:1 title "Title"
hmset Setting multiple hash values hmset News:1 title content "Content" is_valid 1
hmget Get multiple hash values hmget News:1 title content is_valid
hdel Delete a hash value hdel News:1 title
hkeys Get all keys hkeys News:1
hvals Get all values hvals News:1
hlen Gets the number of hash containing fields (attributes) hlen News:1
hexists Judgment of existence hexists News:1 title

python operation string

import redis


class Test_String(object):
    def __init__(self):
        self.r = redis.StrictRedis(host='localhost', port=6379, db=0)

    def test_set(self):
        """
        //Set a value
        :return:
        """
        res = self.r.set('user2','Joshua')
        print(res)

    def test_get(self):
        """
        //Get a value
        :return:
        """
        res = self.r.get('user2')
        print(res)

    def test_mset(self):
        """
        //Setting multiple key-value pairs
        :return:
        """
        d = {'user3': 'qi', 'user4': 'shuai'}
        res = self.r.mset(d)
        print(res)

    def test_mget(self):
        """
        //Get multiple key-value pairs
        :return:
        """
        d = ['user3', 'user4']
        res = self.r.mget(d)
        print(res)

    def test_del(self):
        """
        //Delete a key-value pair
        :return:
        """
        res = self.r.delete('user3')
        print(res)

    def test_incr(self):
        """
        //Increase 1
        :return:
        """
        res = self.r.incr('num')
        print(res)

    def test_decr(self):
        """
        //Reduce 1
        :return:
        """
        res = self.r.decr('num')
        print(res)

    def test_append(self):
        """
        //Adding strings
        :return:
        """
        res = self.r.append('user3','qi')
        print(res)

def main():
    t = Test_String()
    # t.test_mset()
    # t.test_mget()
    # t.test_del()
    # t.test_set()
    # t.test_get()
    # t.test_incr()
    # t.test_decr()
    t.test_append()

if __name__ == '__main__':
    main()

python operation list

import redis


class Test_List(object):
    def __init__(self):
        self.r = redis.StrictRedis(host='localhost', port=6379, db=0)

    def test_push(self):
        l_eat = ['Joshua', 'Amy']
        lres = self.r.lpush('eat2', *l_eat)
        print(lres)
        rres = self.r.rpush('eat2', *l_eat)
        print(rres)

    def test_pop(self):
        res = self.r.lpop('eat2')
        print(res)
        res = self.r.rpop('eat2')
        print(res)

    def test_lindex(self):
        # Get the value of an offset
        res = self.r.lindex('eat2',0)
        print(res)

    def test_lrange(self):
        res = self.r.lrange('eat2',0,2)  # Obtaining the value of an offset
        print(res)
        res = self.r.lrange('eat2',0,-1)  # Get all the values in the list
        print(res)

    def test_ltrim(self):
        res = self.r.ltrim('eat2', 1,2)  # Steal a value and delete other values
        print(res)
        res = self.r.lrange('eat2', 0, -1)
        print(res)

    def test_bpop(self):
        res = self.r.blpop('eat2',timeout=3)  # Delete an element from the left end of the list in three seconds
        print(res)
        res = self.r.brpop('eat2',timeout=3)  # Delete an element from the right end of the list in three seconds
        print(res)

    def test_rpoplpush(self):
        res = self.r.rpoplpush('mylist', 'youlist')  # Delete an element from the right side of mylist and add it to the left-most side of youlist
        print(res)

    def test_brpoplpush(self):
        # Delete an element from the right side of mylist and add it to the left-most side of youlist. If mylist is empty, wait for 3 seconds.
        res = self.r.brpoplpush('mylist', 'youlist',timeout=3)
        print(res)

    def test_pushx(self):
        # Insert a data to the left of the list when the key exists
        res = self.r.lpushx('youlist', 1)
        print(res)

        # Right end
        res = self.r.rpushx('itslist',1)
        print(res)


if __name__ == '__main__':
    t = Test_List()
    # t.test_push()
    # t.test_pop()
    # t.test_lindex()
    # t.test_lrange()
    # t.test_ltrim()
    # t.test_blpop()
    # t.test_rpoplpush()
    # t.test_brpoplpush()
    t.test_pushx()

python operation set

import redis


class Test_Set(object):
    def __init__(self):
        self.r = redis.StrictRedis(host='localhost',port=6379,db=0)

    def test_sadd(self):
        data = ['cat', 'dog']
        res = self.r.sadd('zoo1', *data)
        print(res)
        res = self.r.smembers('zoo1')  # Get all the elements of the collection
        print(res)

    def test_srem(self):
        # data = ['cat', 'dog']
        # res = self.r.srem('zoo', *data)  # Delete multiple elements
        res = self.r.srem('zoo','dog')  # Delete a single element
        print(res)
        res = self.r.smembers('zoo')
        print(res)

    def test_sinter(self):  # Get the intersection of two sets
        res = self.r.sinter('zoo','zoo1')
        print(res)

    def test_sunion(self):  # Get the union of two sets
        res = self.r.sunion('zoo','zoo1')
        print(res)

    def test_sdiff(self):  # Get the difference between two sets
        res = self.r.sdiff('zoo','zoo1')
        print(res)


if __name__ == '__main__':
    t = Test_Set()
    # t.test_sadd()
    # t.test_srem()
    # t.test_sinter()
    # t.test_sunion()
    t.test_sdiff()

python operation hash

import redis


class Test_Hash(object):
    def __init__(self):
        self.r = redis.StrictRedis(host='localhost', port=6379, db=0)

    def test_hset(self):  # Set a hash value
        res = self.r.hset('News:1', 'Title', 'News Title')
        print(res)

    def test_hdel(self):  # Delete a hash value
        res = self.r.hdel('News:1', 'Title')
        print(res)

    def test_hget(self):  # Get a value
        res = self.r.hget('News:1', 'Title')
        print(res)

    def test_heists(self):  # Judgment of existence
        res = self.r.hexists('News:1', 'Title')
        print(res)

    def test_hgetall(self):  # Get all hashes
        res = self.r.hgetall('News:1')
        print(res)

    def test_hmset(self):  # Setting up multiple hashes
        data = {'content':'this is content', 'data':'20190101'}
        res = self.r.hmset('News:1', data)
        print(res)

    def test_hmget(self):  # Get multiple hashes
        fields = ['content', 'data']
        res = self.r.hmget('News:1',fields)
        print(res)

    def test_hkeys(self):  # Get all keys
        res = self.r.hkeys('News:1')
        print(res)

    def test_hvalues(self):  # Get all values
        res = self.r.hvals('News:1')
        print(res)

    def test_hlen(self):  # Get the number of fields
        res = self.r.hlen('News:1')
        print(res)

    def test_hsetnx(self):  # Set a hash value, but not if it exists
        res = self.r.hsetnx('News:1', 'content', 'fuck')
        print(res)


if __name__ == '__main__':
    t = Test_Hash()
    # t.test_hset()
    # t.test_hdel()
    # t.test_hget()
    # t.test_heists()
    # t.test_hgetall()
    # t.test_hmset()
    # t.test_hmget()
    # t.test_hkeys()
    # t.test_hvalues()
    # t.test_hlen()
    t.test_hsetnx()

Posted by thepip3r on Tue, 17 Sep 2019 00:43:25 -0700