Memcached 是一个免费的开源高性能内存中键值数据存储。 它最常用于通过从数据库调用的结果缓存各种对象来加速应用程序。
在本教程中,我们将介绍在 Ubuntu 18.04 上安装和配置最新版 Memcached 的过程。 相同的说明适用于 Ubuntu 16.04 和任何基于 Ubuntu 的发行版。
必要条件
在继续本教程之前,请确保以具有sudo权限的用户身份登录。
安装Memcached
Memcached 软件包包含在默认的 Ubuntu 18.04 存储库中。 安装非常简单,只需按照以下步骤操作:
01、首先更新apt包列表:
[linuxmi@linux:~/www.linuxmi.com]$ sudo apt update
02、键入以下命令安装Memcached:
[linuxmi@linux:~/www.linuxmi.com]$ sudo apt install memcached libmemcached-tools
libmemcached-tools包包含几个用于管理Memcached服务器的命令行工具。
[linuxmi@linux:~/www.linuxmi.com]$ sudo add-apt-repository ‘deb [arch=amd64] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse’
03、安装完成后,Memcached服务将自动启动。 要检查服务的状态,请输入以下命令:
[linuxmi@linux:~/www.linuxmi.com]$ sudo systemctl status memcached
[sudo] linuxmi 的密码:
输出类似如下:
● memcached.service – memcached daemon
Loaded: loaded (/lib/systemd/system/memcached.service; enabled; vendor preset
Active: active (running) since Sun 2020-04-19 20:14:38 CST; 8min ago
Docs: man:memcached(1)
Main PID: 810 (memcached)
Tasks: 10 (limit: 4637)
CGroup: /system.slice/memcached.service
└─810 /usr/bin/memcached -m 64 -p 11211 -u memcache -l 127.0.0.1 -P /
4月 19 20:14:38 linux systemd[1]: Started memcached daemon.
就是这样,此时你已经在你的Ubuntu 18.04服务器上安装并运行了Memcached。配置Memcached
可以通过编辑/etc/memcached.conf文件来配置Memcached。 默认配置设置足以满足大多数用户的需求。
默认情况下,Memcached配置为仅侦听localhost。 如果连接到服务器的客户端也在同一主机上运行,则无需更改默认配置文件。
远程访问
如果配置不当,Memcached可用于执行分布式拒绝服务(DDoS)攻击。 如果要允许远程访问Memcached服务器,则需要配置防火墙并仅允许从受信任的客户端访问Memcached UDP端口11211。
以下示例假定您要通过专用网络连接到Memcached服务器。 服务器IP为192.168.100.20,客户端的IP地址为192.168.100.30
Ubuntu附带了一个名为UFW的防火墙配置工具。 默认情况下,已安装UFW但未启用。 在启用UFW防火墙之前,首先添加允许传入SSH连接的规则:
[linuxmi@linux:~/www.linuxmi.com]$ sudo ufw allow 22
允许192.168.10.218这个IP访问11211这个端口:
[linuxmi@linux:~/www.linuxmi.com]$ sudo ufw allow from 192.168.10.218 to any port 11211
键入以下命令启用UFW:
[linuxmi@linux:~/www.linuxmi.com]$ sudo ufw status
配置防火墙后,下一步是编辑Memcached配置并将Memcached服务设置为侦听服务器的专用网络接口:
为此,请打开memcached.conf配置文件:
[linuxmi@linux:~/www.linuxmi.com]$ sudo nano /etc/memcached.conf
找到以-l 127.0.0.1开头的行,并将127.0.0.1替换为服务器IP地址192.168.10.201。
/etc/memcached.conf
# Specify which IP address to listen on. The default is to listen on all IP add$
# This parameter is one of the only security measures that memcached has, so ma$
# it’s listening on a firewalled interface.
-l 192.168.10.201

[linuxmi@linux:~/www.linuxmi.com]$ sudo systemctl restart memcached
您现在可以从远程位置连接到Memcached服务器。
连接到Memcached
要连接到Memcached服务器,您需要使用特定于语言的客户端。
PHP
要将Memcached用作PHP应用程序(如WordPress,Drupal,Joomla或Magento)的缓存数据库,您需要安装php-memcached扩展:
[linuxmi@linux:~/www.linuxmi.com]$ sudo apt install php-memcached
Python
有几个Python库可以与memcache进行交互。 您可以使用pip安装首选库:
[linuxmi@linux:~/www.linuxmi.com]$ pip install pymemcache
[linuxmi@linux:~/www.linuxmi.com]$ pip install python-memcached
总结
现在,您已经学习了如何在 Ubuntu 18.04 服务器上安装 Memcached。有关此主题的更多信息,请参阅Memcached Wiki。