Redis is an open source data structure server with an in-memory dataset that does much more than simple key/value storage thanks to its built-in data types.
Redis是具有内存数据集的开源数据结构服务器,由于其内置的数据类型,它的功能远不止简单的键/值存储。
It was started in 2009 by Salvatore Sanfilippo and because of its popularity quickly grew, being chosen by big companies like VMware (who later hired Sanfilippo to work on the project full time), GitHub, Craigslist, Disqus, Digg, Blizzard, Instagram, and more (see redis.io/topics/whos-using-redis).
它由Salvatore Sanfilippo于2009年启动,由于其受欢迎程度Swift提高,被VMware等大型公司(后来聘请Sanfilippo全职从事该项目),GitHub,Craigslist,Disqus,Digg,Blizzard,Instagram和更多信息(请参阅redis.io/topics/whos-using-redis )。
You can use Redis as a session handler, which is especially useful if you are using a multi-server architecture behind a load balancer. Redis also has a publish/subscribe system, which is great for creating an online chat or a live booking system. Documentation and more information on Redis and all of its commands can be found on the project’s website, redis.io.
您可以将Redis用作会话处理程序,如果您在负载均衡器后面使用多服务器体系结构,则该功能特别有用。 Redis还具有发布/订阅系统,非常适合创建在线聊天或实时预订系统。 可在项目的网站redis.io上找到有关Redis及其所有命令的文档和更多信息。
There is a lot of argument whether Redis or Memcache is better, though as the benchmarks show they perform pretty much on par with each other for basic operations. Redis has more features than Memcache, such as in-memory and disk persistence, atomic commands and transactions, and not logging every change to disk but rather server-side data structures instead.
尽管基准测试表明 Redis或Memcache在基本操作上的性能相当,但仍有很多争论。 Redis具有比Memcache更多的功能,例如内存和磁盘持久性,原子命令和事务,而不是将每次更改都记录到磁盘上,而是记录在服务器端数据结构中。
In this article we’ll take a look at some of the basic but powerful commands that Redis has to offer using the Predis library.
在本文中,我们将介绍Redis必须使用Predis库提供的一些基本但功能强大的命令。
Redis is easy to install, and brief installation instructions are published on the product’s download page. From my own experience, if you are running Ubuntu then you will get an error if you do not have TCL installed (simply run sudo apt-get install tcl). Once Redis is installed, you can run the server:
Redis易于安装,并且简短的安装说明发布在产品的下载页面上 。 根据我的经验,如果您正在运行Ubuntu,那么如果您未安装TCL,则会收到一条错误消息(只需运行sudo apt-get install tcl)。 一旦安装了Redis,就可以运行服务器:
gafitescu@ubun2:~$ /usr/local/bin/redis-server * The server is now ready to accept connections on port 6379There are Redis client libraries available for many languages and are listed on the Redis website, often times with several available for each language! For PHP, there are five. For this article I’ll be using the Predis library, but you may also want to look into phpredis which gets compiled and installed as a PHP module.
Redis客户端库可用于多种语言,并在Redis网站上列出 ,通常每种语言都有几种可用! 对于PHP,有五个。 在本文中,我将使用Predis库 ,但您可能还想研究phpredis ,它已被编译并安装为PHP模块。
If you have Git installed on your machine like I do, all you need to do is clone the Predis repository. Otherwise you’ll need to download the ZIP archive and unpack it.
如果像我一样在计算机上安装了Git,则只需克隆Predis存储库即可。 否则,您需要下载ZIP存档并解压缩。
gafitescu@ubun2:~$ git clone git://github.com/nrk/predis.gitTo test everything out, create the file test.php with the following content to test if you can successfully connect to the running Redis server with Predis:
要测试所有内容,请创建包含以下内容的文件test.php ,以测试您是否可以使用Predis成功连接到正在运行的Redis服务器:
<?php require "predis/autoload.php"; PredisAutoloader::register(); // since we connect to default setting localhost // and 6379 port there is no need for extra // configuration. If not then you can specify the // scheme, host and port to connect as an array // to the constructor. try { $redis = new PredisClient(); /* $redis = new PredisClient(array( "scheme" => "tcp", "host" => "127.0.0.1", "port" => 6379)); */ echo "Successfully connected to Redis"; } catch (Exception $e) { echo "Couldn't connected to Redis"; echo $e->getMessage(); }When you run it, you should hopefully see the message “Successfully connected to Redis”.
运行它时,您应该希望看到消息“成功连接到Redis”。
In this section you’ll gain an overview of the most commonly used commands that Redis has to offer. Memcache has an equivalent for most of them, so if you are familiar with Memcache then this listing will look familiar to you.
在本节中,您将概述Redis必须提供的最常用命令。 Memcache与它们中的大多数等效,因此,如果您熟悉Memcache,则此清单对您来说会很熟悉。
The most important commands used with Redis are SET, GET, and EXISTS. You can use these commands to store and check on temporary information that is going to be accessed multiple times, typically in a key/value manner. For example:
与Redis一起使用的最重要的命令是SET , GET和EXISTS 。 您可以使用这些命令来存储和检查将要多次访问的临时信息,通常以键/值的方式。 例如:
<?php $redis->set("hello_world", "Hi from php!"); $value = $redis->get("hello_world"); var_dump($value); echo ($redis->exists("Santa Claus")) ? "true" : "false";The set() method is used to set a value to a particular key, in this case the key is “hello_world” and the value is “Hi from php!” The get() method retrieves the value for the key, again in this case “hello_world”. The exists() method reports back whether the provided key is found or not in Redis’ storage.
set()方法用于为特定键设置值,在这种情况下,键为“ hello_world”,值为“ Hi from php!”。 get()方法检索密钥的值,在这种情况下还是“ hello_world”。 exists()方法报告在Redis的存储中是否找到了提供的密钥。
The key is not restricted to alphanumeric characters and the underscore. The following will work just as well:
该键不限于字母数字字符和下划线。 以下内容同样适用:
<?php $redis->set("I 2 love Php!", "Also Redis now!"); $value = $redis->get("I 2 love Php!");The INCR and DECR commands are used to increment and decrement values and are a great way to maintain counters. INCR and DECR increment/decrement their values by 1; you can also use INCRBY and DECRBY to adjust by larger intervals. Here’s an example:
INCR和DECR命令用于递增和递减值,并且是维护计数器的好方法。 INCR和DECR将其值增加/减少1; 您还可以使用INCRBY和DECRBY调整较大的间隔。 这是一个例子:
<?php // increment the number of views by 1 for an article // with id 234 $redis->incr("article_views_234"); // increment views for article 237 by 5 $redis->incrby("article_views_237", 5); // decrement views for article 237 $redis->decr("article_views_237"); // decrement views for article 237 by 3 $redis->decrby("article_views_237", 3);As I mentioned earlier, Redis has built-in data types. You may be thinking that it’s odd to have data types in a NoSQL key-value storage system such as Redis, but this would be useful for developers to structure the information in a more meaningful way and perform specific operations which is typically much faster when the data is typed. Redis’ data types are:
如前所述,Redis具有内置的数据类型。 您可能会认为在NoSQL键值存储系统(例如Redis)中具有数据类型是很奇怪的,但这对于开发人员以更有意义的方式构造信息并执行特定操作很有用,这通常会在数据被输入。 Redis的数据类型是:
String – the basic data type used in Redis in which you can store from few characters to the content of an entire file.
字符串 – Redis中使用的基本数据类型,您可以在其中存储从几个字符到整个文件内容的数据。
List – a simple list of strings order by the insertion of its elements. You can add and remove elements from both the list’s head and tail, so you can use this data type to implement queues.
列表 –一个简单的字符串列表,通过插入其元素来排序。 您可以从列表的开头和结尾添加和删除元素,因此可以使用此数据类型实现队列。
Hash – a map of string keys and string values. In this way you can represent objects (think of it as a one-level deep JSON object).
哈希 -字符串键和字符串值的映射。 通过这种方式,您可以表示对象(将其视为一个一级的深度JSON对象)。
Set – an unordered collection of strings where you can add, remove, and test for existence of members. The one constraint is that you are not allowed to have repeated members.
Set –字符串的无序集合,您可以在其中添加,删除和测试成员的存在。 一个限制是不允许您有重复的成员。
Sorted set – a particular case of the set data type. The difference is that every member has and associated score that is used order the set from the smallest to the greatest score.
排序集 –集合数据类型的特殊情况。 不同之处在于,每个成员都有一个和相关的分数,该分数用于按从最小到最大的分数对集合进行排序。
So far I’ve only demonstrated strings, but there are commands that make working with data in other data types just as easy.
到目前为止,我仅演示了字符串,但是有些命令使处理其他数据类型中的数据变得同样容易。
These commands are used to work with Redis’ hash data type:
这些命令用于处理Redis的哈希数据类型:
HSET – sets the value for a key on the the hash object.
HSET –设置哈希对象上键的值。
HGET – gets the value for a key on the hash object.
HGET –获取哈希对象上键的值。
HINCRBY – increment the value for a key of the hash object with a specified value.
HINCRBY –用指定的值递增哈希对象的键的值。
HDEL – remove a key from the object.
HDEL –从对象中删除密钥。
HGETALL – get all keys and data for a object.
HGETALL –获取对象的所有键和数据。
Here’s an example that demonstrates their usage:
这是一个演示其用法的示例:
<?php $redis->hset("taxi_car", "brand", "Toyota"); $redis->hset("taxi_car", "model", "Yaris"); $redis->hset("taxi_car", "license number", "RO-01-PHP"); $redis->hset("taxi_car", "year of fabrication", 2010); $redis->hset("taxi_car", "nr_starts", 0); /* $redis->hmset("taxi_car", array( "brand" => "Toyota", "model" => "Yaris", "license number" => "RO-01-PHP", "year of fabrication" => 2010, "nr_stats" => 0) ); */ echo "License number: " . $redis->hget("taxi_car", "license number") . "<br>"; // remove license number $redis->hdel("taxi_car", "license number"); // increment number of starts $redis->hincrby("taxi_car", "nr_starts", 1); $taxi_car = $redis->hgetall("taxi_car"); echo "All info about taxi car"; echo "<pre>"; var_dump($taxi_car); echo "</pre>";These are the important commands for working with the list type in Redis. A Redis list is similar to an array in PHP, and offer a great support for implementing queues, stacks, or a capped collection of a certain number of elements.
这些是在Redis中使用列表类型的重要命令。 Redis列表类似于PHP中的数组,并且为实现队列,堆栈或一定数量的元素的上限集合提供了强大的支持。
LPUSH – prepends element(s) to a list.
LPUSH –将元素添加到列表中。
RPUSH – appends element(s) to a list.
RPUSH –将元素添加到列表。
LPOP – removes and retrieves the first element of a list.
LPOP –删除并检索列表的第一个元素。
RPOP – removes and retrieves the last element of a list.
RPOP –删除并检索列表的最后一个元素。
LLEN – gets the length of a list.
LLEN –获取列表的长度。
LRANGE – gets elements from a list.
LRANGE –从列表中获取元素。
<?php $list = "PHP Frameworks List"; $redis->rpush($list, "Symfony 2"); $redis->rpush($list, "Symfony 1.4"); $redis->lpush($list, "Zend Framework"); echo "Number of frameworks in list: " . $redis->llen($list) . "<br>"; $arList = $redis->lrange($list, 0, -1); echo "<pre>"; print_r($arList); echo "</pre>"; // the last entry in the list echo $redis->rpop($list) . "<br>"; // the first entry in the list echo $redis->lpop($list) . "<br>";Most likely, when you set a key you don’t want it to be saved forever because after a certain period of time it’s not likely to be relevant anymore. You’ll need to update its value or delete it to reduce memory usage for better performance. Redis offers four commands that let you handle data persistence easily.
最有可能的是,当您设置密钥时,您不希望它永远被保存,因为经过一段时间后,它不再具有相关性。 您需要更新或删除它的值以减少内存使用,以获得更好的性能。 Redis提供了四个命令,可让您轻松处理数据持久性。
EXPIRE – sets an expiration timeout (in seconds) for a key after which it and its value will be deleted.
EXPIRE –设置密钥的过期超时(以秒为单位),此后将删除它及其值。
EXPIREAT – sets and expiration time using a unix timestamp that represents when the key and value will be deleted.
EXPIREAT –使用unix时间戳设置和终止时间,该时间戳表示何时删除键和值。
TTL – gets the remaining time left to live for a key with an expiration.
TTL –获取剩余的剩余生存时间,用于过期的密钥。
PERSIST – removes the expiration on the given key.
PERSIST –删除给定密钥上的到期。
<?php // set the expiration for next week $redis->set("expire in 1 week", "I have data for a week"); $redis->expireat("expire in 1 week", strtotime("+1 week")); $ttl = $redis->ttl("expire in 1 week"); // will be 604800 seconds // set the expiration for one hour $redis->set("expire in 1 hour", "I have data for an hour"); $redis->expire("expire in 1 hour", 3600); $ttl = $redis->ttl("expire in 1 hour"); // will be 3600 seconds // never expires $redis->set("never expire", "I want to leave forever!");We looked at just a short list of Redis commands in this article, but you can check the whole list of commands on the Redis website. Indeed Redis has much more to offer than just being a Memcache replacement.
在本文中,我们仅查看了Redis命令的简短列表,但是您可以在Redis网站上查看命令的整个列表。 实际上,Redis提供的不仅仅是提供Memcache替代品。
Redis is here for the long run; it has a growing community, support for all major languages, and offers durability and high-availability with master-slave replication. Redit is open source, so if you’re a C guru then you can fork its source code from GitHub and become a contributor.
Redis从长远来看; 它具有不断发展的社区,支持所有主要语言,并通过主从复制提供持久性和高可用性。 Redit是开源的,因此,如果您是C大师,则可以从GitHub派生其源代码并成为贡献者。
If you’re looking for more information beyond the project site, you might want to consider checking out two great Redis books, Redis Cookbook and Redis: The Definitive Guide.
如果您想在项目站点之外寻找更多信息,则可以考虑查看两本出色的Redis书籍:《 Redis Cookbook》和《 Redis:The Definitive Guide》 。
翻译自: https://www.sitepoint.com/an-introduction-to-redis-in-php-using-predis/
相关资源:php 使用redis锁限制并发访问类