1. Introduction

This article continues with another common way to store data: Memcached

Memcached: A high performance distributed memory object caching system that uses memory caching to reduce database load, thereby reducing database load and increasing site load speed

Memcached is a compact key-value storage system that can store various types of data: strings, objects, images, files, videos, and more

Because the Memcached data is stored in memory, all data will be lost after the service or system is restarted. In addition, when the Memcached capacity reaches a specified value, the unused cache is automatically removed based on the LRU algorithm

Memcached protocol is simple and powerful, easy to develop and compatible with most development languages. This article will cover the proper Python posture for handling Memcached

2. Prepare

The following uses memcached-server installation in Centos 7.8 as an example

First, install Memcached on your cloud server

# yum install memcachedCopy the code

Use the whereis command to query the directory where Memcached is installed

# /usr/bin/memcached [root@VM-16-11-centos ~]# whereis memcached /usr/bin/memcached /usr/share/man/man1/memcached.1.gzCopy the code

Then, start the Memcached service with the command line and parameters

# -u: user running memcached # -l: set which IP can be connected to the service, 0.0.0.0: Allow /usr/bin/memcached -p 11211 -m 64m -d -u root -l 0.0.0.0Copy the code

Common startup parameters include:

  • -d: runs in the background through the daemon process

  • -m: indicates the maximum allocated memory. The default size is 64 MB

  • -u: user running Memcached

  • -l: specifies the IP address that can access the Memecache service. If you want to access the Internet, set this parameter to 0.0.0.0

  • -p: specifies the port number monitored by Memcached. The default port number is 111211

  • -c: indicates the maximum number of concurrent connections. The default value is 1024

Next, open the firewall port

Note that if the server is a cloud server, you need to enable the port number in the security group

Firewall-cmd --add-port=11211/ TCP --permanent firewall -- CMD --reloadCopy the code

To do this, we have two ways to manipulate data

Respectively is:

1. Connect to the Memecached service through Telnet and use the command line to perform operations

Telnet IP address 11211Copy the code

2. Use Python, Java, and Php to manipulate Memcached data

In Python, for example, you need to install the python-memcached dependency

Pip3 install python-memcachedCopy the code

3. The actual combat

Before we can manipulate the data in Memcache, we need to import Memcache, use the Client() method to specify the Memecache service to operate on, and build a data connection object

Def __init__(self): self. MC = memcache.client ([' IP :11211'], debug=True)Copy the code

Next, we’ll talk about Python’s methods for manipulating data, using examples such as add, query, update, append, delete, etc

1. Add operations

Add (key,value,timeout)

The timeout parameter indicates the data retention period. The timeout is automatically cleared

Note that if the key to be inserted does not exist in the original dataset, a new record will be added to the dataset. Otherwise, a failure is added and a warning is displayed

Def __add(self): """ """ # MemCached: MemCached: MemCached: MemCached: MemCached: MemCached: MemCached: MemCached: MemCached: while expecting 'STORED', got unexpected response 'NOT_STORED' self.mc.add("name", "xag", time=60 * 5) self.mc.add("age", 23)Copy the code

2. Query operations

Memcached query operations are as follows:

  • Query a single record by Key

  • Query multiple records through a list of multiple keys

The corresponding method of single record query is get(key).

Def __query_one(self, key): """ return: Result = self.mc.get(key) print(' key:', key, ",value:", result)Copy the code

Query multiple records by get_multi(keys)

Def __query_many(self, keys): """ "" values = self.mc.get_multi(keys) # dict print(type(values)) print(' ', values)Copy the code

3. Update operation

The update operation consists of three methods:

  • Update a record. If the key does not exist, the update fails

    Replace (key,value)

  • Update a record, or add a new record if the key does not exist

    Set (key,value)

  • Update multiple records, and if there are nonexistent keys, add the corresponding key-value pairs to the dataset

    Set_multi ({key1:value1… })

The specific example code is as follows:

Def __update_default(self): """ def __update_default(self): """ replace, set, set_multi :return: Replace ("name","xag1") # self.mc.replace("name","xag1") # self.__query_one("name") # Set ("name", "xag2") # self.__query_one("name") # 3 Set_multi ({"name": "xag3", "age": 28}) self.__query_many(["name", "age"])Copy the code

4. Append operations

The append operation is equivalent to modifying the value of a key and appending data to the header or tail

Among them:

  • Append (STR) : Appends a piece of data to the end

  • Prepend (STR) : adds a piece of data to the header

The practice code is as follows:

Def __update_append(self): """ def __update_append(self): """ Self.mc. append("name"," I am the new content ") self.__query_one("name") # 2, prepend # Self.mc. prepend("name"," header added ") self.__query_one("name")Copy the code

5. Delete operations

Similar to the query operation, the delete operation supports the deletion of a single key-value pair and the deletion of multiple key-value pairs

  • Delete (key) : deletes a key/value pair

  • Delete_multi (keys) : deletes all Key pairs corresponding to all keys in the list

The corresponding operation code is as follows:

def __delete(self): "" Delete data containing: Delete, delete_multi :return:delete_multi """ # 1, delete # delete single key value pair # self.mc.delete("age") # self.__query_one("age") # Keys = ["name","age"] self.mc.delete_multi(keys) self.__query_many(keys)Copy the code

4. The last

This article uses Python to perform general operations on the Memcached data. You can read the article for more complex operations

I have uploaded all the source code to the background, follow the public account “AirPython” reply “dball” can get all the source code

If you think the article is good, please like, share, leave a message, because this will be my continuous output of more high-quality articles the strongest power!