直接安装
```
sudo apt install memcached
```
然后就会默认在后台运行。
```
$ ps aux|grep memcached
memcache 87827 0.0 0.3 326560 3796 ? Ssl 17:48 0:00 /usr/bin/memcached -m 64 -p 11211 -u memcache -l 127.0.0.1
```
来一个PHP的demo(需要安装sudo apt install php-memcached)。
```
<?php
# 先建立到本地memcached的连接。
$mem = new Memcached();
$mem->addServer("127.0.0.1", 11211);
# 然后尝试读取某key的值(因为没有设置,所以这个值还没有)
$key1 = "cqq";
$result = $mem->get($key1);
# 第一次判断这个值发现没有之后,会通过->add()函数将值加到memcached,第二次就会有了。
if ($result){
echo $result;
}else {
echo "[!] no matching key found! I'm gonna add that now.";
$mem->add($key1, "caiqiqi") or die("[!] couldn't save any values to memcached!");
}
?>
```
然后想要命令行访问,直接连接他的TCP端口,然后
```
$ nc -v 127.0.0.1 11211
Connection to 127.0.0.1 11211 port [tcp/*] succeeded!
get cqq
VALUE cqq 0 7
caiqiqi
END
```
## 用memcached缓存mysql查询到的数据
### php demo
```
<?php
$mem = new Memcached();
$mem->addServer("127.0.0.1", 11211);
# 准备工作:先创建数据库,账户,密码
# mysql> create database mem_test;
# mysql> grant all on mem_test.* to test@'localhost' identified by 'testing123';
# mysql> use mem_test;
# mysql> create table sample_data(id int, name varchar(30));
# mysql> insert into sample_data values(1, "some_data");
$servername = "127.0.0.1";
$username = "test";
$password = "testing123";
$dbname = "mem_test";
$conn = new mysqli($servername, $username, $password, $dbname) or dir(mysql_error());
$query_str = "select id from sample_data where name = 'some_data'";
$query_key = "KEY" . md5($query_str); # 通过加上md5值生成一个唯一的key
print $query_key;
$result = $mem->get($query_key);
if ($result){
print "<p> Data was: ". $result[0] . "</p>";
print "<p> Caching success!</p><p>Retrived data from memcached!</p>";
} else{
$result = $conn->query($query_str) or dir(mysql_error());
$row = $result->fetch_assoc();
#var_dump($row);
$mem->set($query_key, $row['id'], 100); # 过期时间s
print "<p>Data not found in memcached.</p><p>Data retrieved from MySQL and stored in memcached for next time.</p>";
}
```
执行完上述php代码之后(命令行或者WEB),再去memcached里去查找。
```
caikiki@ubuntu:~$ nc -v 127.0.0.1 11211
Connection to 127.0.0.1 11211 port [tcp/*] succeeded!
get KEYc029fe1cf78a2428b554004188ab9468
VALUE KEYc029fe1cf78a2428b554004188ab9468 0 1
1
END
```
参考:
http://www.runoob.com/memcached/memcached-connection.html
https://www.digitalocean.com/community/tutorials/how-to-install-and-use-memcache-on-ubuntu-14-04