php redis入门_PHP Redis入门

php redis入门

什么是Redis? (What is Redis?)

Redis created by Salvatore Sanfilippo is an open source, in-memory data structure server with advanced key-value cache and store, often referred to as a NoSQL database. It is also referred to as a data structure server, since it can store strings, hashes, lists, sets, sorted sets, and more.

Salvatore Sanfilippo创建的Redis是一种开源的内存中数据结构服务器,具有高级键值缓存和存储,通常称为NoSQL数据库。 它也可以称为数据结构服务器,因为它可以存储字符串,哈希,列表,集合,排序集合等。

The essence of a key-value store is the ability to store some data, called a value inside a key. This data can later be retrieved only if we know the exact key used to store it.

键值存储的本质是能够存储一些数据(称为键内的值)的能力。 仅当我们知道用于存储数据的确切密钥时,以后才能检索该数据。

Redis的用法 (Usage of Redis)

Salvatore Sanfilippo (creator of Redis) said Redis can be used to replace a RDBMS database. Now, although nothing is impossible, I think it would be a bad idea, because using a key-value store for things, like a full-text search, might be painful. Especially, when you consider ACID compliance and syncing data in a key-value store: painful.

Salvatore Sanfilippo(Redis的创建者)表示,Redis可用于替换RDBMS数据库。 现在,尽管没有什么不可能,但我认为这不是一个好主意,因为对诸如全文搜索之类的东西使用键值存储可能会很痛苦。 特别是,当您考虑遵守ACID并在键值存储中同步数据时:痛苦。

Below are just a few uses of Redis, though there are many more than this.

以下只是Redis的一些用途,尽管还有更多用途。

  • Caching can be used in the same manner as memcached.

    可以与memcached相同的方式使用缓存。
  • Leaderboards or related problems.

    排行榜或相关问题。
  • Counting stuff.

    数东西。
  • Real time analysis.

    实时分析。
  • Deletion and filtering.

    删除和过滤。
  • Show latest item listings in your home page.

    在您的主页上显示最新的物品清单。

本文目的 (Aim of this Article)

This article's aim is not to show you the syntax of Redis (you can learn about Redis's syntax here), in this article, we will learn how to use Redis in PHP.

本文的目的不是向您展示Redis的语法(您可以在此处了解Redis的语法),在本文中,我们将学习如何在PHP中使用Redis。

安装Redis (Install Redis)

Redis is pretty easy to install and the instructions, included, are for both Windows and Linux users.

Redis非常易于安装,其中的说明适用于Windows和Linux用户。

在Linux上安装Redis (Install Redis on Linux)

To install Redis on Linux, is pretty simple, but you'll need TCL installed if you don't have TCL installed. You can simply run:

要在Linux上安装Redis非常简单,但是如果没有安装TCL,则需要安装TCL。 您可以简单地运行:

$ sudo apt-get install tcl

To install Redis:

要安装Redis:

$ wget http://download.redis.io/releases/redis-2.8.19.tar.gz
$ tar xzf redis-2.8.19.tar.gz
$ cd redis-2.8.19
$ make

Note: 2.8.19 should be replaced with the latest stable version of Redis.

注意: 2.8.19应替换为最新的稳定版本的Redis。

All Redis binaries are saved in the SRC Folder. To start the server simply:

所有Redis二进制文件都保存在SRC文件夹中。 要简单地启动服务器:

$ src/redis-server

在Windows上安装 (Install on Windows)

Redis installation on Windows is very easy, just visit this link, download a package, and install.

在Windows上安装Redis非常容易,只需访问此链接 ,下载软件包并安装即可。

为PHP安装Predis Redis客户端 (Install Predis a Redis Client for PHP)

Predis is a Redis Client for PHP. It is well written and has a lot of support from the community. To use Predis just clone the repository into your working directory:

Predis是PHP的Redis客户端。 它写得很好,得到了社区的大力支持。 要使用Predis,只需将存储库克隆到您的工作目录中:

$ git clone git://github.com/nrk/predis.git

连接到Redis (Connecting to Redis)

First, we'll require the Redis Autoloader and register it. Then we'll wrap the client in a try catch block. The connection setting for connecting to Redis on a local server is different from connecting to a remote server.

首先,我们需要Redis自动加载器并进行注册。 然后,我们将客户端包装在try catch块中。 连接到本地服务器上的Redis的连接设置与连接到远程服务器上的连接设置不同。

<?php
require "predis/autoload.php";
PredisAutoloader::register();

try {
	$redis = new PredisClient();

	// This connection is for a remote server
	/*
		$redis = new PredisClient(array(
		    "scheme" => "tcp",
		    "host" => "153.202.124.2",
		    "port" => 6379
		));
	*/
}
catch (Exception $e) {
	die($e->getMessage());
}

Now that we have successfully connected to the Redis server, let's start using Redis.

现在我们已成功连接到Redis服务器,让我们开始使用Redis。

Redis数据类型 (Redis Datatypes)

Redis supports a range of datatypes and you might wonder what a NOSQL key-value store has to do with datatypes? Well, these datatypes help developers store data in a meaningful way and can make data retrieval faster. Here are some of the datatypes supported by Redis:

Redis支持多种数据类型,您可能想知道NOSQL键值存储与数据类型有什么关系? 好的,这些数据类型可以帮助开发人员以有意义的方式存储数据,并使数据检索更快。 以下是Redis支持的一些数据类型:

  • String: Similar to Strings in PHP.

    字符串:类似于PHP中的字符串。
  • List: Similar to a single dimensional array in PHP. You can push, pop, shift and unshift, the elements that are placed in order or insertion FIFO (first in, first out).

    列表:类似于PHP中的一维数组。 您可以推入,弹出,移位和取消移位,按顺序放置的元素或插入FIFO(先进先出)。
  • Hash: Maps between string fields and string values. They are the perfect data type to represent objects (e.g.: A User with a number of fields like name, surname, and so forth).

    哈希:在字符串字段和字符串值之间映射。 它们是代表对象的理想数据类型(例如:具有多个字段(例如名称,姓氏等)的用户)。
  • Set: Similar to list, except that it has no order and each element may appear only once.

    设置:与列表类似,除了它没有顺序而且每个元素只能出现一次。
  • Sorted Set: Similar to Redis Sets with a unique feature of values stored in set. The difference is that each member of a Sorted Set is associated with score, used to order the set from the smallest score to the largest.

    排序集:类似于Redis集,具有存储在集中的值的独特功能。 区别在于,排序集的每个成员都与得分相关联,用于对集合从最小得分到最大得分进行排序。

Others are bitmaps and hyperloglogs, but they will not be discussed in this article, as they are pretty dense.

其他的是位图和超级日志,但是由于它们非常密集,因此在本文中将不再讨论。

吸气剂和二传手 (Getters and Setters)

In Redis, the most important commands are SET, GET and EXISTS. These commands are used to store, check, and retrieve data from a Redis server. Just like the commands, the Predis class can be used to perform Redis operations by methods with the same name as commands. For example:

在Redis中,最重要的命令是SETGETEXISTS 。 这些命令用于存储,检查和从Redis服务器检索数据。 就像命令一样,Predis类可用于通过与命令同名的方法来执行Redis操作。 例如:

<?php
// sets message to contian "Hello world"
$redis->set(';message';, ';Hello world';);

// gets the value of message
$value = $redis->get('message');

// Hello world
print($value); 

echo ($redis->exists('message')) ? "Oui" : "please populate the message key";

增量和减量 (Increments and Decrements)

INCR and DECR are commands used to either decrease or increase a value.

INCRDECR是用于减小或增大值的命令。

<?php
$redis->set("counter", 0);

$redis->incr("counter"); // 1
$redis->incr("counter"); // 2

$redis->decr("counter"); // 1

We can also increase the values of the counter key by larger integer values or we can decrease the value of the counter key with the INCRBY and DECRBY commands.

我们还可以将计数器键的值增加较大的整数值,或者可以使用INCRBYDECRBY命令减小计数器键的值。

<?php
$redis->set("counter", 0);

$redis->incrby("counter", 15); // 15
$redis->incrby("counter", 5);  // 20

$redis->decrby("counter", 10); // 10

使用清单 (Working with Lists)

There are a few basic Redis commands for working with lists and they are:

有一些用于处理列表的基本Redis命令,它们是:

  • LPUSH: adds an element to the beginning of a list

    LPUSH:将元素添加到列表的开头
  • RPUSH: add an element to the end of a list

    RPUSH:将元素添加到列表的末尾
  • LPOP: removes the first element from a list and returns it

    LPOP:从列表中删除第一个元素并返回它
  • RPOP: removes the last element from a list and returns it

    RPOP:从列表中删除最后一个元素并返回它
  • LLEN: gets the length of a list

    LLEN:获取列表的长度
  • LRANGE: gets a range of elements from a list

    LRANGE:从列表中得到一个范围内的元素

Simple List Usage:

简单列表用法:

<?php
$redis->rpush("languages", "french"); // [french]
$redis->rpush("languages", "arabic"); // [french, arabic]

$redis->lpush("languages", "english"); // [english, french, arabic]
$redis->lpush("languages", "swedish"); // [swedish, english, french, arabic]

$redis->lpop("languages"); // [english, french, arabic]
$redis->rpop("languages"); // [english, french]

$redis->llen("languages"); // 2

$redis->lrange("languages", 0, -1); // returns all elements
$redis->lrange("languages", 0, 1); // [english, french]

使用哈希 (Working with Hashes)

A hash in Redis is a map between one string field and string values, like a one-to-many relationship. The commands associated with hashes in Redis are:

Redis中的哈希是一个字符串字段和字符串值之间的映射,就像一对多关系一样。 与Redis中的哈希相关的命令是:

  • HSET: sets a key-value on the hash

    HSET:在哈希上设置键值
  • HGET: gets a key-value on the hash

    HGET:在哈希上获取键值
  • HGETALL: gets all key-values from the hash

    HGETALL:从哈希中获取所有键值
  • HMSET: mass assigns several key-values to a hash

    HMSET:质量为哈希分配几个键值
  • HDEL: deletes a key from the object

    HDEL:从对象中删除密钥
  • HINCRBY: increments a key-value from the hash with a given value.

    HINCRBY:使用给定值从哈希中增加键值。
<?php
$key = ';linus torvalds';;
$redis->hset($key, ';age';, 44);
$redis->hset($key, ';country';, ';finland';);
$redis->hset($key, 'occupation', 'software engineer');
$redis->hset($key, 'reknown', 'linux kernel');
$redis->hset($key, 'to delete', 'i will be deleted');

$redis->get($key, 'age'); // 44
$redis->get($key, 'country')); // Finland

$redis->del($key, 'to delete');

$redis->hincrby($key, 'age', 20); // 64

$redis->hmset($key, [
    'age' => 44,
    'country' => 'finland',
    'occupation' => 'software engineer',
    'reknown' => 'linux kernel',
]);

// finally
$data = $redis->hgetall($key);
print_r($data); // returns all key-value that belongs to the hash
/*
    [
        'age' => 44,
        'country' => 'finland',
        'occupation' => 'software engineer',
        'reknown' => 'linux kernel',
    ]
*/

使用集 (Working with Sets)

The list of commands associated with sets include: - SADD: adds a N number of values to the key - SREM: removes N number of values from a key - SISMEMBER: if a value exists - SMEMBERS: lists of values in the set.

与集合相关联的命令的列表包括: - SADD:在所述一组值的列表:SMEMBERS -如果值存在 - -从密钥移除了N个值的数SISMEMBER SREM增加值,以键的N个。

<?php
$key = "countries";
$redis->sadd($key, ';china';);
$redis->sadd($key, ['england', 'france', 'germany']);
$redis->sadd($key, 'china'); // this entry is ignored

$redis->srem($key, ['england', 'china']);

$redis->sismember($key, 'england'); // false

$redis->smembers($key); // ['france', 'germany']

设置到期和持久性 (Set Expiry and Persistence)

Since Redis is an in-memory data store, you would probably not store data forever. Therefore, this brings us to EXPIRE, EXPIREAT, TTL, PERSIST - EXPIRE: sets an expiration time, in seconds, for the key after which it is deleted - EXPIREAT: sets an expiration time using unix timestamps for the key after which it is deleted - TTL: gets the remaining time left for a key expiration - PERSIST: makes a key last forever by removing the expiration timer from the key.

由于Redis是内存数据存储,因此您可能不会永远存储数据。 因此,这使我们进入EXPIREEXPIREATTTLPERSIST - EXPIRE:设置密钥的到期时间(以秒为单位),然后将其删除-EXPIREAT:使用unix时间戳设置密钥的到期时间,之后将其删除-TTL 获取密钥到期的剩余时间-PERSIST:通过从密钥中删除到期计时器,使密钥永久使用。

$key = "expire in 1 hour";
$redis->expire($key, 3600); // expires in 1 hour
$redis->expireat($key, time() + 3600); // expires in 1 hour

sleep(600); // don't try this, just an illustration for time spent

$redis->ttl($key); // 3000, ergo expires in 50 minutes

$redis->persist($key); // this will never expire.

结论 (Conclusion)

The commands listed in this article are just a handful of many existing Redis commands (see more redis commands).

本文列出的命令只是许多现有Redis命令中的少数几个(请参阅更多redis命令 )。

Redis的未来 (Future of Redis)

Redis is a better replacement for memcached, as it is faster, scales better (supports master-slave replication), supports datatypes that many (Facebook, Twitter, Instagram) have dropped memcached for Redis. Redis is open source and many brilliant programmers from the open-source community have contributed patches.

Redis可以更好地替代memcached,因为它速度更快,扩展性更好(支持主从复制),支持许多类型(Facebook,Twitter,Instagram)已为Redis删除memcached的数据类型。 Redis是开源的,来自开源社区的许多杰出的程序员都做出了贡献。

其他来源 (Other sources)

翻译自: https://scotch.io/tutorials/getting-started-with-redis-in-php

php redis入门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值