Memcached 简明教程

Memcached - Quick Guide

Memcached - Overview

Memcached 是一个开源、高性能的分布式内存缓存系统,旨在通过减轻数据库负载来加速动态 Web 应用程序。它是一个存储在内存中的字符串、对象等键值对字典,源自数据库调用、API 调用或页面渲染。

Memcached is an open source, high-performance, distributed memory caching system intended to speed up dynamic web applications by reducing the database load. It is a key-value dictionary of strings, objects, etc., stored in the memory, resulting from database calls, API calls, or page rendering.

Memcached 于 2003 年由 Brad Fitzpatrick 为 LiveJournal 开发。然而,它现在正被 Netlog、Facebook、Flickr、Wikipedia、Twitter 和 YouTube 等公司使用。

Memcached was developed by Brad Fitzpatrick for LiveJournal in 2003. However, it is now being used by Netlog, Facebook, Flickr, Wikipedia, Twitter, and YouTube among others.

Memcached 的主要特性如下:

The key features of Memcached are as follows −

  1. It is open source.

  2. Memcached server is a big hash table.

  3. It significantly reduces the database load

  4. It is perfectly efficient for websites with high database load.

  5. It is distributed under Berkeley Software Distribution (BSD) license.

  6. It is a client-server application over TCP or UDP.

Memcached is not −

  1. a persistent data store

  2. a database

  3. application-specific

  4. a large object cache

  5. fault-tolerant or highly available

Memcached - Environment

Installing Memcached on Ubuntu

要在 Ubuntu 上安装 Memcached,请进入终端并键入以下命令:

To install Memcached on Ubuntu, go to terminal and type the following commands −

$sudo apt-get update
$sudo apt-get install memcached

Confirming Memcached Installation

要确认 Memcached 是否已安装,您需要运行以下给定的命令。此命令表示 Memcached 正在默认端口 11211 上运行。

To confirm if Memcached is installed or not, you need to run the command given below. This command shows that Memcached is running on the default port 11211.

$ps aux | grep memcached

要在不同的端口上运行 Memcached 服务器,请执行下面给出的命令。此命令在 TCP 端口 11111 上启动服务器,并在 UDP 端口 11111 上监听,作为一个守护进程。

To run Memcached server on a different port, execute the command given below. This command starts the server on the TCP port 11111 and listens on the UDP port 11111 as a daemon process.

$memcached -p 11111 -U 11111 -u user -d

您可以通过一次安装运行 memcached 服务器的多个实例。

You can run multiple instances of Memcached server through a single installation.

Memcached Java Environment Setup

在您的 Java 程序中使用 Memcached,您需要下载 * spymemcached-2.10.3.jar* ,并将此 jar 设置到类路径中。

To use Memcached in your Java program, you need to download spymemcached-2.10.3.jar and setup this jar into the classpath.

Memcached - Connection

要连接到 Memcached 服务器,您需要在 HOST 和 PORT 名称上使用 telnet 命令。

To connect to a Memcached server, you need to use the telnet command on HOST and PORT names.

Syntax

Memcached telnet 命令的基本语法如下所示:

The basic syntax of Memcached telnet command is as shown below −

$telnet HOST PORT

此处 HOSTPORT 分别是 Memcached 服务器正在执行的机器的 IP 和端口号。

Here, HOST and PORT are machine IP and port number respectively, on which the Memcached server is executing.

Example

以下示例演示如何连接到 Memcached 服务器并执行一个简单的设定和获取命令。假设 Memcached 服务器正在主机 127.0.0.1 和端口 11211 上运行。

The following example shows how to connect to a Memcached server and execute a simple set and get command. Assume that the Memcached server is running on host 127.0.0.1 and port 11211.

$telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
// now store some data and get it from memcached server
set tutorialspoint 0 900 9
memcached
STORED
get tutorialspoint
VALUE tutorialspoint 0 9
memcached
END

Connection from Java Application

要从您的 java 程序连接 Memcached 服务器,您需要将 Memcached jar 添加到您的类路径中,如前一章所示。假设 Memcached 服务器正在主机 127.0.0.1 和端口 11211 上运行。-

To connect the Memcached server from your java program, you need to add the Memcached jar into your classpath as shown in the previous chapter. Assume that the Memcached server is running on host 127.0.0.1 and port 11211. −

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server sucessfully");

      //not set data into memcached server
      System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").done);

      //Get value from cache
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successfully
set status:true
Get from Cache:memcached.

终端可能还会显示一些信息消息,这些消息可以忽略。

The terminal may show few informational messages too, those can be ignored.

Memcached - Set Data

Memcached set 命令用于为新键或现有键设置新值。

Memcached set command is used to set a new value to a new or existing key.

Syntax

Memcached set 命令的基本语法如下所示:

The basic syntax of Memcached set command is as shown below −

set key flags exptime bytes [noreply]
value

语法中的关键字的说明如下:

The keywords in the syntax are as described below −

  1. key − It is the name of the key by which data is stored and retrieved from Memcached.

  2. flags − It is the 32-bit unsigned integer that the server stores with the data provided by the user, and returns along with the data when the item is retrieved.

  3. exptime − It is the expiration time in seconds. 0 means no delay. If exptime is more than 30 days, Memcached uses it as UNIX timestamp for expiration.

  4. bytes − It is the number of bytes in the data block that needs to be stored. This is the length of the data that needs to be stored in Memcached.

  5. noreply (optional) - It is a parameter that informs the server not to send any reply.

  6. value − It is the data that needs to be stored. The data needs to be passed on the new line after executing the command with the above options.

Output

命令的输出如下所示:

The output of the command is as shown below −

STORED
  1. STORED indicates success.

  2. ERROR indicates incorrect syntax or error while saving data.

Example

在以下示例中,我们将 tutorialspoint 用作键,并将值 Memcached 设置为其值,其过期时间为 900 秒。

In the following example, we use tutorialspoint as the key and set value Memcached in it with an expiration time of 900 seconds.

set tutorialspoint 0 900 9
memcached
STORED
get tutorialspoint
VALUE tutorialspoint 0 9
Memcached
END

Set Data Using Java Application

要在 Memcached 服务器中设置键,您需要使用 Memcached set 方法。

To set a key in Memcached server, you need to use Memcached set method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server sucessfully");
      System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").done);

      // Get value from cache
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successfully
set status:true
Get from Cache:memcached

Memcached - Add Data

Memcached add 命令用于为新键设置值。如果键已存在,则它给出输出 NOT_STORED。

Memcached add command is used to set a value to a new key. If the key already exists, then it gives the output NOT_STORED.

Syntax

Memcached add 的基本语法如下所示 −

The basic syntax of Memcached add command is as shown below −

add key flags exptime bytes [noreply]
value

语法中的关键字的说明如下:

The keywords in the syntax are as described below −

  1. key − It is the name of the key by which data is stored and retrieved from Memcached.

  2. flags − It is the 32-bit unsigned integer that the server stores with the data provided by the user, and returns along with the data when the item is retrieved.

  3. exptime − It is the expiration time in seconds. 0 means no delay. If exptime is more than 30 days, Memcached uses it as a UNIX timestamp for expiration.

  4. bytes − It is the number of bytes in the data block that needs to be stored. This is the length of the data that needs to be stored in Memcached.

  5. noreply (optional) − It is a parameter that informs the server not to send any reply.

  6. value − It is the data that needs to be stored. The data needs to be passed on the new line after executing the command with the above options.

Output

命令的输出如下所示:

The output of the command is as shown below −

STORED
  1. STORED indicates success.

  2. NOT_STORED indicates the data is not stored in Memcached.

Example

在以下示例中,我们使用“key”作为键,并以 900 秒的过期时间在其内添加值 Memcached。

In the following example, we use ‘key’ as the key and add the value Memcached in it with an expiration time of 900 seconds.

add key 0 900 9
memcached
STORED
get key
VALUE key 0 9
Memcached
END

Failure Output

add key 0 900 5
redis
NOT_STORED

Add Data Using Java Application

若要将数据添加到 Memcached 服务器,您需要使用 Memcached add 方法。

To add data in a Memcached server, you need to use the Memcached add method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server successful");
      System.out.println("add status:"+mcc.add("tutorialspoint", 900, "redis").done);
      System.out.println("add status:"+mcc.add("tp", 900, "redis").done);

      // Get value from cache
      System.out.println("Get from Cache tp:"+mcc.get("tp"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successful
add status:false
add status:true
Get from Cache tp:redis

Memcached - Replace Data

Memcached replace 命令用于替换现有键的值。如果键不存在,则会输出 NOT_STORED。

Memcached replace command is used to replace the value of an existing key. If the key does not exist, then it gives the output NOT_STORED.

Syntax

Memcached replace 的基本语法如下所示 −

The basic syntax of Memcached replace command is as shown below −

replace key flags exptime bytes [noreply]
value

语法中的关键字的说明如下:

The keywords in the syntax are as described below −

  1. key − It is the name of the key by which data is stored and retrieved from Memcached.

  2. flags − It is the 32-bit unsigned integer that the server stores with the data provided by the user, and returns along with the data when the item is retrieved.

  3. exptime − It is the expiration time in seconds. 0 means no delay. If exptime is more than 30 days, Memcached uses it as a UNIX timestamp for expiration.

  4. bytes − It is the number of bytes in the data block that needs to be stored. This is the length of the data that needs to be stored in the Memcached.

  5. noreply (optional) − It is a parameter that informs the server not to send any reply.

  6. value − It is the data that needs to be stored. The data needs to be passed on the new line after executing the command with the above options.

Output

命令的输出如下所示:

The output of the command is as shown below −

STORED
  1. STORED indicates success.

  2. NOT_STORED indicates the data is not stored in Memcached.

Example

在以下示例中,我们使用“key”作为键,并以 900 秒的过期时间在其内存储 memcached。此后,将使用值“redis”替换相同的键。

In the following example, we use ‘key’ as the key and store memcached in it with an expiration time of 900 seconds. After this, the same key is replaced with the value ‘redis’.

add key 0 900 9
memcached
STORED
get key
VALUE key 0 9
memcached
END
replace key 0 900 5
redis
get key
VALUE key 0 5
redis
END

Replace Data Using Java Application

若要替换 Memcached 服务器中的数据,您需要使用 Memcached replace 方法。

To replace data in a Memcached server, you need to use the Memcached replace method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server sucessfully");
      System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").done);

      // Get value from cache
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));

      // now replace the existing data
      System.out.println("Replace cache:"+mcc.replace("tutorialspoint", 900, "redis").done);

      // get the updated data
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successfully
set status:true
Get from Cache:memcached
Replace cache:true
Get from Cache:redis

Memcached - Append Data

Memcached append 命令用于在现有键中添加一些数据。将在键的现有数据后存储数据。

Memcached append command is used to add some data in an existing key. The data is stored after the existing data of the key.

Syntax

Memcached append 的基本语法如下所示 −

The basic syntax of Memcached append command is as shown below −

append key flags exptime bytes [noreply]
value

语法中的关键字的说明如下−

The keywords in the syntax are as described below−

  1. key − It is the name of the key by which data is stored and retrieved from Memcached.

  2. flags − It is the 32-bit unsigned integer that the server stores with the data provided by the user, and returns along with the data when the item is retrieved.

  3. exptime − It is the expiration time in seconds. 0 means no delay. If exptime is more than 30 days, Memcached uses it as a UNIX timestamp for expiration.

  4. bytes − It is the number of bytes in the data block that needs to be stored. This is the length of the data that needs to be stored in Memcached.

  5. noreply (optional) − It is a parameter that informs the server not send any reply.

  6. value − It is the data that needs to be stored. The data needs to be passed on the new line after executing the command with the above options.

Output

命令的输出如下所示:

The output of the command is as shown below −

STORED
  1. STORED indicates success.

  2. NOT_STORED indicates the key does not exist in the Memcached server.

  3. CLIENT_ERROR indicates error.

Example

在以下示例中,我们尝试向一个不存在的键添加一些数据。因此,Memcached 返回 NOT_STORED 。在此之后,我们设置一个键并将数据追加到其中。

In the following example, we try to add some data in a key that does not exist. Hence, Memcached returns NOT_STORED. After this, we set one key and append data into it.

append tutorials 0 900 5
redis
NOT_STORED
set tutorials 0 900 9
memcached
STORED
get tutorials
VALUE tutorials 0 14
memcached
END
append tutorials 0 900 5
redis
STORED
get tutorials
VALUE tutorials 0 14
memcachedredis
END

Append Data Using Java Application

若要将数据追加到 Memcached 服务器,您需要使用 Memcached append 方法。

To append data in a Memcached server, you need to use the Memcached append method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server successful");
      System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").isDone());

      // Get value from cache
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));

      // now append some data into existing key
      System.out.println("Append to cache:"+mcc.append("tutorialspoint", "redis").isDone());

      // get the updated key
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successful
set status:true
Get from Cache:memcached
Append to cache:true
Get from Cache:memcachedredis

Memcached - Prepend Data

Memcached prepend 命令用于在现有键中添加一些数据。将在键的现有数据前存储数据。

Memcached prepend command is used to add some data in an existing key. The data is stored before the existing data of the key.

Syntax

Memcached prepend 命令的基本语法如下所示 −

The basic syntax of Memcached prepend command is as shown below −

prepend key flags exptime bytes [noreply]
value

语法中的关键字的说明如下−

The keywords in the syntax are as described below−

  1. key − It is the name of the key by which data is stored and retrieved in Memcached.

  2. flags − It is the 32-bit unsigned integer that the server stores with the data provided by the user, and returns along with the data when the item is retrieved.

  3. exptime − It is the expiration time in seconds. 0 means no delay. If exptime is more than 30 days, Memcached uses it as a UNIX timestamp for expiration.

  4. bytes − It is the number of bytes in the data block that needs to be stored. This is the length of the data that needs to be stored in Memcached.

  5. noreply (optional) −It is a parameter that informs the server not send any reply.

  6. value − It is the data that needs to be stored. Data needs to be passed on the new line after executing the command with the above options.

Output

命令的输出如下所示:

The output of the command is as shown below −

STORED
  1. STORED indicates success.

  2. NOT_STORED indicates the key does not exist in the Memcached server.

  3. CLIENT_ERROR indicates error.

Example

在以下示例中,我们在不存在的密钥中添加了一些数据。因此,Memcached 返回 NOT_STORED 。在此之后,我们设置一个密钥并在其中置入数据。

In the following example, we add some data in a key that does not exist. Hence, Memcached returns NOT_STORED. After this, we set one key and prepend data into it.

prepend tutorials 0 900 5
redis
NOT_STORED
set tutorials 0 900 9
memcached
STORED
get tutorials
VALUE tutorials 0 14
memcached
END
prepend tutorials 0 900 5
redis
STORED
get tutorials
VALUE tutorials 0 14
redismemcached
END

Prepend Data Using Java Application

要向 Memcached 服务器中置入数据,你需要使用 Memcached prepend 方法。

To prepend data in a Memcached server, you need to use the Memcached prepend method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {
      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server successful");
      System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").isDone());

      // Get value from cache
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));

      // now append some data into existing key
      System.out.println("Prepend to cache:"+mcc.prepend("tutorialspoint", "redis").isDone());

      // get the updated key
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successful
set status:true
Get from Cache:memcached
Prepend to cache:true
Get from Cache:redismemcached

Memcached - CAS Command

CAS 代表 Check-And-Set 或 Compare-And-Swap。Memcached CAS 命令用于在数据自上次获取以来未更新时设置数据。如果密钥不存在于 Memcached 中,则它返回 NOT_FOUND

CAS stands for Check-And-Set or Compare-And-Swap. Memcached CAS command is used to set the data if it is not updated since last fetch. If the key does not exist in Memcached, then it returns NOT_FOUND.

Syntax

Memcached CAS 命令的基本语法如下所示 −

The basic syntax of Memcached CAS command is as shown below −

set key flags exptime bytes unique_cas_key [noreply]
value

语法中的关键字的说明如下−

The keywords in the syntax are as described below−

  1. key − It is the name of the key by which data is stored and retrieved from Memcached.

  2. flags − It is the 32-bit unsigned integer that the server stores with the data provided by the user, and returns along with the data when the item is retrieved.

  3. exptime − It is the expiration time in seconds. 0 means no delay. If exptime is more than 30 days, Memcached uses it as a UNIX timestamp for expiration.

  4. bytes − It is the number of bytes in the data block that needs to be stored. This is the length of the data that needs to be stored in Memcached.

  5. unique_cas_key − It is the unique key get from gets command.

  6. noreply (optional) − It is a parameter that informs the server not to send any reply.

  7. value − It is the data that needs to be stored. Data needs to be passed on new line after executing the command with the above options.

Output

命令的输出如下所示:

The output of the command is as shown below −

STORED
  1. STORED indicates success.

  2. ERROR indicates error while saving data or wrong syntax.

  3. EXISTS indicates that someone has modified the CAS data since last fetch.

  4. NOT_FOUND indicates that the key does not exist in the Memcached server.

Example

要在 Memcached 中执行 CAS 命令,你需要从 Memcached gets 命令中获取 CAS 令牌。

To execute a CAS command in Memcached, you need to get a CAS token from the Memcached gets command.

cas tp 0 900 9
ERROR
cas tp 0 900 9 2
memcached
set tp 0 900 9
memcached
STORED
gets tp
VALUE tp 0 9 1
memcached
END
cas tp 0 900 5 2
redis
EXISTS
cas tp 0 900 5 1
redis
STORED
get tp
VALUE tp 0 5
redis
END

CAS Using Java Application

要从 Memcached 服务器中获取 CAS 数据,你需要使用 Memcached gets 方法。

To get CAS data from a Memcached server, you need to use Memcached gets method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

     // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server successful");
      System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").isDone());

      // Get cas token from cache
      long castToken = mcc.gets("tutorialspoint").cas;
      System.out.println("Cas token:"+castToken);

      // now set new data in memcached server
      System.out.println("Now set new data:"+mcc.cas("tutorialspoint",
      castToken, 900, "redis"));
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successful
set status:true
Cas token:3
Now set new data:OK
Get from Cache:redis

Memcached - Get Data

Memcached get 命令用于获取存储在密钥上的值。如果密钥不存在于 Memcached 中,则它不会返回任何内容。

Memcached get command is used to get the value stored at key. If the key does not exist in Memcached, then it returns nothing.

Syntax

Memcached get 命令的基本语法如下所示 −

The basic syntax of Memcached get command is as shown below −

get key

Example

在以下示例中,我们使用 tutorialspoint 作为密钥,并在其中存储 memcached,其过期时间为 900 秒。

In the following example, we use tutorialspoint as the key and store memcached in it with an expiration time of 900 seconds.

set tutorialspoint 0 900 9
memcached
STORED
get tutorialspoint
VALUE tutorialspoint 0 9
memcached
END

Get Data Using Java Application

要从 Memcached 服务器获取数据,你需要使用 Memcached get 方法。

To get data from a Memcached server, you need to use the Memcached get method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {
      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server sucessfully");
      System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").done);

     // Get value from cache
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successfully
set status:true
Get from Cache:memcached

Memcached - Get CAS Data

Memcached gets 命令用于获取带有 CAS 令牌的值。如果 Memcached 中不存在该密钥,则它将不返回任何内容。

Memcached gets command is used to get the value with CAS token. If the key does not exist in Memcached, then it returns nothing.

Syntax

Memcached gets 命令的基本语法如下所示:

The basic syntax of Memcached gets command is as shown below −

get key

Example

set tutorialspoint 0 900 9
memcached
STORED
gets tutorialspoint
VALUE tutorialspoint 0 9 1
memcached
END

在此示例中,我们使用 tutorialspoint 作为密钥,并将 memcached 存储在其中,其到期时间为 900 秒。

In this example, we use tutorialspoint as the key and store memcached in it with an expiration time of 900 seconds.

Get CAS Data Using Java Application

若要从 Memcached 服务器获取 CAS 数据,您需要使用 Memcached gets 方法。

To get CAS data from a Memcached server, you need to use the Memcached gets method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server sucessfully");
      System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").done);

      // Get value from cache
      System.out.println("Get from Cache:"+mcc.gets("tutorialspoint"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successfully
set status:true
Get from Cache:{CasValue 2/memcached}

Memcached - Delete Key

Memcached delete 命令用于从 Memcached 服务器中删除现有密钥。

Memcached delete command is used to delete an existing key from the Memcached server.

Syntax

Memcached delete 命令的基本语法如下所示:

The basic syntax of Memcached delete command is as shown below −

delete key [noreply]

Output

CAS 命令可能生成以下结果之一:

CAS command may produce one of the following result −

  1. DELETED indicates successful deletion.

  2. ERROR indicates error while deleting data or wrong syntax.

  3. NOT_FOUND indicates that the key does not exist in the Memcached server.

Example

在此示例中,我们使用 tutorialspoint 作为密钥,并将 memcached 存储在其中,其到期时间为 900 秒。此后,它将删除存储的密钥。

In this example, we use tutorialspoint as a key and store memcached in it with an expiration time of 900 seconds. After this, it deletes the stored key.

set tutorialspoint 0 900 9
memcached
STORED
get tutorialspoint
VALUE tutorialspoint 0 9
memcached
END
delete tutorialspoint
DELETED
get tutorialspoint
END
delete tutorialspoint
NOT_FOUND

Delete Data Using Java Application

若要从 Memcached 服务器删除数据,您需要使用 Memcached delete 方法。

To delete data from a Memcached server, you need to use the Memcached delete method.

Example

import java.net.InetSocketAddress;
import java.util.concurrent.Future;

import net.spy.memcached.MemcachedClient;

public class MemcachedJava {
   public static void main(String[] args) {

      try{

         // Connecting to Memcached server on localhost
         MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
         System.out.println("Connection to server sucessful.");

         // add data to memcached server
         Future fo = mcc.set("tutorialspoint", 900, "World's largest online tutorials library");

         // print status of set method
         System.out.println("set status:" + fo.get());

         // retrieve and check the value from cache
         System.out.println("tutorialspoint value in cache - " + mcc.get("tutorialspoint"));

         // try to add data with existing key
         Future fo = mcc.delete("tutorialspoint");

         // print status of delete method
         System.out.println("delete status:" + fo.get());

         // retrieve and check the value from cache
         System.out.println("tutorialspoint value in cache - " + mcc.get("codingground"));

         // Shutdowns the memcached client
         mcc.shutdown();

      }catch(Exception ex)
         System.out.println(ex.getMessage());
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successful
set status:true
tutorialspoint value in cache - World's largest online tutorials library
delete status:true
tutorialspoint value in cache - null

Memcached - Delete data

Memcached delete 命令用于从 Memcached 服务器中删除现有密钥。

Memcached delete command is used to delete an existing key from the Memcached server.

Syntax

Memcached delete 命令的基本语法如下所示:

The basic syntax of Memcached delete command is as shown below −

delete key

如果成功删除该密钥,则它将返回 DELETED。如果未找到该密钥,则它将返回 NOT_FOUND,否则将返回 ERROR。

If the key is successfully deleted, then it returns DELETED. If the key is not found, then it returns NOT_FOUND, otherwise it returns ERROR.

Example

在此示例中,我们使用 tutorialspoint 作为密钥,并将 memcached 存储在其中,其到期时间为 900 秒。此后,它将删除存储的密钥。

In this example, we use tutorialspoint as a key and store memcached in it with an expiration time of 900 seconds. After this, it deletes the stored key.

set tutorialspoint 0 900 9
memcached
STORED
get tutorialspoint
VALUE tutorialspoint 0 9
memcached
END
delete tutorialspoint
DELETED
get tutorialspoint
END
delete tutorialspoint
NOT_FOUND

Delete Data Using Java Application

若要从 Memcached 服务器删除数据,您需要使用 Memcached delete 方法。

To delete data from a Memcached server, you need to use the Memcached delete method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server successful");
      System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").done);

      // Get value from cache
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));

      // delete value from cache
      System.out.println("Delete from Cache:"+mcc.delete("tutorialspoint").isDone());

      // check whether value exists or not
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successful
set status:true
Get from Cache:memcached
Delete from Cache:true
Get from Cache:null

Memcached - Increment Decrement Data

Memcached incrdecr 命令用于增加或减少现有密钥的数值。如果未找到该密钥,则它将返回 NOT_FOUND 。如果该密钥不是数字,则它将返回 CLIENT_ERROR cannot increment or decrement non-numeric value 。否则,将返回 ERROR

Memcached incr and decr commands are used to increment or decrement the numeric value of an existing key. If the key is not found, then it returns NOT_FOUND. If the key is not numeric, then it returns CLIENT_ERROR cannot increment or decrement non-numeric value. Otherwise, ERROR is returned.

Syntax - incr

Memcached incr 命令的基本语法如下所示:

The basic syntax of Memcached incr command is as shown below −

incr key increment_value

Example

在此示例中,我们使用 visitors 作为密钥,并最初在其中设置 10,然后将其增加 5。

In this example, we use visitors as key and set 10 initially into it, thereafter we increment the visitors by 5.

set visitors 0 900 2
10
STORED
get visitors
VALUE visitors 0 2
10
END
incr visitors 5
15
get visitors
VALUE visitors 0 2
15
END

Syntax - decr

Memcached decr 命令的基本语法如下所示:

The basic syntax of Memcached decr command is as shown below

decr key decrement_value

Example

set visitors 0 900 2
10
STORED
get visitors
VALUE visitors 0 2
10
END
decr visitors 5
5
get visitors
VALUE visitors 0 1
5
END

Incr/Decr Using Java Application

若要在 Memcached 服务器中增加或减少数据,您需要分别使用 Memcached incr or decr 方法。

To increment or decrement data in a Memcached server, you need to use Memcached incr or decr methods respectively.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server sucessfully");
      System.out.println("set status:"+mcc.set("count", 900, "5").isDone());

      // Get value from cache
      System.out.println("Get from Cache:"+mcc.get("count"));

      // now increase the stored value
      System.out.println("Increment value:"+mcc.incr("count", 2));

      // now decrease the stored value
      System.out.println("Decrement value:"+mcc.decr("count", 1));

      // now get the final stored value
      System.out.println("Get from Cache:"+mcc.get("count"));
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successfully
set status:true
Get from Cache:5
Increment value:7
Decrement value:6
Get from Cache:6

Memcached - Stats

Memcached stats 命令用于返回服务器统计信息,如 PID、版本、连接等。

Memcached stats command is used to return server statistics such as PID, version, connections, etc.

Syntax

Memcached stats 命令的基本语法如下所示:

The basic syntax of Memcached stats command is as shown below −

stats

Example

stats
STAT pid 1162
STAT uptime 5022
STAT time 1415208270
STAT version 1.4.14
STAT libevent 2.0.19-stable
STAT pointer_size 64
STAT rusage_user 0.096006
STAT rusage_system 0.152009
STAT curr_connections 5
STAT total_connections 6

STAT connection_structures 6
STAT reserved_fds 20
STAT cmd_get 6
STAT cmd_set 4
STAT cmd_flush 0
STAT cmd_touch 0
STAT get_hits 4
STAT get_misses 2
STAT delete_misses 1
STAT delete_hits 1

STAT incr_misses 2
STAT incr_hits 1
STAT decr_misses 0
STAT decr_hits 1
STAT cas_misses 0
STAT cas_hits 0
STAT cas_badval 0
STAT touch_hits 0
STAT touch_misses 0
STAT auth_cmds 0

STAT auth_errors 0
STAT bytes_read 262
STAT bytes_written 313
STAT limit_maxbytes 67108864
STAT accepting_conns 1
STAT listen_disabled_num 0
STAT threads 4
STAT conn_yields 0
STAT hash_power_level 16

STAT hash_bytes 524288
STAT hash_is_expanding 0
STAT expired_unfetched 1
STAT evicted_unfetched 0
STAT bytes 142
STAT curr_items 2
STAT total_items 6
STAT evictions 0
STAT reclaimed 1
END

Stats Using Java Application

要从 Memcached 服务器获取统计信息,您需要使用 Memcached stats 方法。

To get stats from a Memcached server, you need to use the Memcached stats method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server successful");
      System.out.println("Stats:"+mcc.stats);
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successful
Stats:[/127.0.0.1:11211:[delete_hits:0, bytes:71, total_items:4,
rusage_system:0.220013, touch_misses:0, cmd_touch:0, listen_disabled_num:0,
auth_errors:0, evictions:0, version:1.4.14, pointer_size:64, time:1417279366,
incr_hits:1, threads:4, expired_unfetched:0, limit_maxbytes:67108864,
hash_is_expanding:0, bytes_read:170, curr_connections:8, get_misses:1,
reclaimed:0, bytes_written:225, hash_power_level:16, connection_structures:9,
cas_hits:0, delete_misses:0, total_connections:11, rusage_user:0.356022,
cmd_flush:0, libevent:2.0.19-stable, uptime:12015, reserved_fds:20,
touch_hits:0, cas_badval:0, pid:1138, get_hits:2, curr_items:1, cas_misses:0,
accepting_conns:1, evicted_unfetched:0, cmd_get:3, cmd_set:2, auth_cmds:0,
incr_misses:1, hash_bytes:524288, decr_misses:1, decr_hits:1, conn_yields:0]]

Memcached - Stats Items

Memcached stats items 命令用于获取按 slab ID 组织的各项统计信息,如计数、年龄、驱逐等。

Memcached stats items command is used to get items statistics such as count, age, eviction, etc. organized by slabs ID.

Syntax

Memcached stats items 命令的基本语法如下所示:

The basic syntax of Memcached stats items command is as shown below −

stats items

Example

stats items
STAT items:1:number 1
STAT items:1:age 7
STAT items:1:evicted 0
STAT items:1:evicted_nonzero 0
STAT items:1:evicted_time 0
STAT items:1:outofmemory 0
STAT items:1:tailrepairs 0
STAT items:1:reclaimed 0
STAT items:1:expired_unfetched 0
STAT items:1:evicted_unfetched 0
END

Memcached - Stats Slabs

Memcached stats slabs 命令显示 Slab 统计信息,例如大小、内存使用情况、命令、数量等,并按 Slab 编号排列。

Memcached stats slabs command displays slabs statistics such as size, memory usage, commands, count etc. organized by slabs ID.

Syntax

Memcached stats slabs 命令的基本语法如下所示:

The basic syntax of Memcached stats slabs command is as shown below −

stats slabs

Example

stats slabs
STAT 1:chunk_size 96
STAT 1:chunks_per_page 10922
STAT 1:total_pages 1
STAT 1:total_chunks 10922
STAT 1:used_chunks 1
STAT 1:free_chunks 10921
STAT 1:free_chunks_end 0
STAT 1:mem_requested 71
STAT 1:get_hits 0
STAT 1:cmd_set 1
STAT 1:delete_hits 0
STAT 1:incr_hits 0
STAT 1:decr_hits 0
STAT 1:cas_hits 0
STAT 1:cas_badval 0
STAT 1:touch_hits 0
STAT active_slabs 1
STAT total_malloced 1048512
END

Memcached - Stats Sizes

Memcached stats sizes 命令提供有关缓存中各个大小的项目大小和数量的信息。信息在两列中返回。第一列是项目大小(向上舍入到最接近的 32 字节边界),第二列是缓存中该大小的项目数量。

Memcached stats sizes command provides information about the sizes and number of items of each size within the cache. The information is returned in two columns. The first column is the size of the item (rounded up to the nearest 32 byte boundary), and the second column is the count of the number of items of that size within the cache.

Syntax

Memcached stats sizes 命令的基本语法如下所示 −

The basic syntax of Memcached stats sizes command is as shown below −

stats sizes

Example

stats sizes
STAT 96 1
END

项目大小统计信息仅可用于确定你正在存储的对象的大小。由于实际的内存分配仅与块大小和页面大小相关,所以该信息只有在仔细调试或诊断会话中才有用。

The item size statistics are useful only to determine the sizes of the objects you are storing. Since the actual memory allocation is relevant only in terms of the chunk size and page size, the information is only useful during a careful debugging or diagnostic session.

Memcached - Clear Data

Memcached flush_all 命令用于从 Memcached 服务器删除所有数据(键值对)。它接受一个名为 time 的可选参数,该参数设置一个时间,在此时间之后将清除 Memcached 数据。

Memcached flush_all command is used to delete all data (key-value pairs) from the Memcached server. It accepts an optional parameter called time that sets a time after which the Memcached data is to be cleared.

Syntax

Memcached flush_all 命令的基本语法如下所示 −

The basic syntax of Memcached flush_all command is as shown below −

flush_all [time] [noreply]

以上命令始终返回 OK。

The above command always returns OK.

Example

在下面的示例中,我们将一些数据存储到 Memcached 服务器,然后清除所有数据。

In the following example, we store some data into the Memcached server and then clear all the data.

set tutorialspoint 0 900 9
memcached
STORED
get tutorialspoint
VALUE tutorialspoint 0 9
memcached
END
flush_all
OK
get tutorialspoint
END

Clear Data Using Java Application

要从 Memcached 服务器清除数据,你需要使用 Memcached flush 方法。

To clear data from a Memcached server, you need to use the Memcached flush method.

Example

import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {

     // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server sucessfully");
      System.out.println("set status:"+mcc.set("count", 900, "5").isDone());

      // Get value from cache
      System.out.println("Get from Cache:"+mcc.get("count"));

      // now increase the stored value
      System.out.println("Increment value:"+mcc.incr("count", 2));

      // now decrease the stored value
      System.out.println("Decrement value:"+mcc.decr("count", 1));

      // now get the final stored value
      System.out.println("Get from Cache:"+mcc.get("count"));

      // now clear all this data
      System.out.println("Clear data:"+mcc.flush().isDone());
   }
}

Output

编译并执行该程序后,您可以看到以下输出:

On compiling and executing the program, you get to see the following output −

Connection to server successfully
set status:true
Get from Cache:5
Increment value:7
Decrement value:6
Get from Cache:6
Clear data:true