Redis的基础应用

一、概念
Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库。

Redis 与其他 key – value 缓存产品有以下三个特点:
Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
– Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储。
– Redis支持数据的备份,即master-slave模式的数据备份。

Redis 优势
– 性能极高 – Redis能读的速度是110000次/s,写的速度是81000次/s 。
– 丰富的数据类型 – Redis支持二进制案例的 Strings, Lists, Hashes, Sets 及 Ordered Sets 数据类型操作。
– 原子 – Redis的所有操作都是原子性的,意思就是要么成功执行要么失败完全不执行。单个操作是原子性的。多个操作也支持事务,即原子性,通过MULTI和EXEC指令包起来。
– 丰富的特性 – Redis还支持 publish/subscribe, 通知, key 过期等等特性。

二、安装
http://www.runoob.com/redis/redis-install.html

三、五种数据类型
Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。

Strings
append – Append a value to a key
get – Get the value of a key
incr, incrBy – Increment the value of a key
set – Set the string value of a key
setRange – Overwrite part of a string at key starting at the specified offset
strLen – Get the length of the value stored in a key

Hashes
hDel – Delete one or more hash fields
hExists – Determine if a hash field exists
hGet – Get the value of a hash field
hGetAll – Get all the fields and values in a hash
hKeys – Get all the fields in a hash
hLen – Get the number of fields in a hash
hMGet – Get the values of all the given hash fields
hMSet – Set multiple hash fields to multiple values
hSet – Set the string value of a hash field
hVals – Get all the values in a hash
hScan – Scan a hash key for members
hStrLen – Get the string length of the value associated with field in the hash

Lists
lPop – Remove and get the first element in a list
lPush – Prepend one or multiple values to a list
lSet – Set the value of an element in a list by its index
rPop – Remove and get the last element in a list
rPush – Append one or multiple values to a list

Sets
sAdd – Add one or more members to a set
sCard, sSize – Get the number of members in a set
sPop – Remove and return one or more members of a set at random
sRandMember – Get one or multiple random members from a set
sScan – Scan a set for members

Sorted sets
zAdd – Add one or more members to a sorted set or update its score if it already exists
zCard, zSize – Get the number of members in a sorted set
zCount – Count the members in a sorted set with scores within the given values
zIncrBy – Increment the score of a member in a sorted set
zInter – Intersect multiple sorted sets and store the resulting sorted set in a new key
zRange – Return a range of members in a sorted set, by index
zRank, zRevRank – Determine the index of a member in a sorted set
zScore – Get the score associated with the given member in a sorted set

四、redis的PHP扩展
扩展 https://github.com/phpredis/phpredis

五、PHP操作redis

Select Code
1
2
3
4
5
<?php
   //连接本地的 Redis 服务
   $redis = new Redis();
   $redis->connect('127.0.0.1', 6379);
?>