Memcached和Redis基础

本文主要介绍Memcached和Redisd的使用基础

Memcached安装和使用

1
2
3
sudo apt-get install memcached
sudo apt-get install php-pecl-memcache
memcached -d -p 11211 -u memcached -m 64 -c 1024 -P /var/run/memcached/memcached.pid

参数说明:

1
2
3
4
5
- d 启动一个守护进程
- p 端口
- m 分配的内存是M
- c 最大运行并发数
- P memcache的pid

php使用代码:

1
2
3
4
5
6
7
8
9
10
<?php
$memcache = new Memcache;
$memcache -> connect('127.0.0.1', 11211);
$memcache -> set('name','yang',0,30);
if(!$memcache->add('name','susan',0, 30)) {
//echo 'susan is exist';
}
$memcache -> replace('name', 'lion', 0, 300);
echo $memcache -> get('name');
//$memcache -> delete('name', 5);

登陆命令:

1
2
printf "stats\r\n" | nc 127.0.0.1 11211
telnet localhost 11211 stats quit退出

Redis使用

Redis的配置文件 端口6379
/etc/redis.conf

1
2
3
4
5
6
7
8
9
启动Redis
redis-server /etc/redis.conf
插入一个值
redis-cli set test "phper.yang"
获取键值
redis-cli get test
关闭Redis
redis-cli shutdown 关闭所有
redis-cli -p 6397 shutdown

php使用代码:

1
2
3
4
5
<?php
$redis=new Redis();
$redis->connect('127.0.0.1',6379);
$redis->set('test', 'Hello World');
echo $redis->get('test');

下面是一个redis的类
Redis Class使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$conf = array(
'sc' => true, //是否开启主从,需要Redis 配置文件配置好
'servers' => array(
'master' => array( //主写
'host' => '127.0.0.1',
'port' => 63888,
'timeout' => 10,
'auth' => 123456,
),
'slave' => array(
array( //从读
'host' => '127.0.0.1',
'port' => 63791,
'timeout' => 10,
'auth' => 123456,
),
array( //从读
'host' => '127.0.0.1',
'port' => 63792,
'timeout' => 10,
'auth' => 123456,
)
),
)
);

关于配置Redis的主从配置说明:

1
2
3
4
5
m.conf  port 6378
~/bin/redis-cli -h 127.0.0.1 -p 6378
s.conf:port: 6379 slaveof 127.0.0.1 6379
~/bin/redis-cli -h 127.0.0.1 -p 6379
RDB(bgsave 命令)

配置文件redis.conf

1
2
3
4
5
6
7
8
9
10
11
12
save 900 1  #900秒内如果超过1个key被修改,则发起快照保存
save 300 10 #300秒内容如超过10个key被修改,则发起快照保存
save 60 10000
save /bgsave
~/.jumbo/bin/dump.rdb
AOF(bgrewriteaof命令)
appendonly yes //启用aof持久化方式
# appendfsync always //每次收到写命令就立即强制写入磁盘,最慢的,但是保证完全的持久化,不推荐使用

appendfsync everysec //每秒钟强制写入磁盘一次,在性能和持久化方面做了很好的折中,推荐
# appendfsync no //完全依赖os,性能最好,持久化没保证

php使用:

1
2
3
4
5
6
$r = $redis->getRedis()->info(); //写数据
print_r("主" . $r['tcp_port']);
$redis->set('id', 100);
$r = $redis->getRedis(false)->info(); //读数据
print_r("从" . $r['tcp_port']);
print_r($redis->getRedis(false)->get('id'));

Memcached和Redis基础
https://brantxiong.github.io/02/17/2014/memcached_and_redis_basic/
作者
Brant Xiong
发布于
2014年2月17日
许可协议