学习在AWS Elasticache上使用PHP和Redis

Caching Services (also known as in-memory databases) like Redis and Memcached are being heavily used in today’s web applications. These in-memory databases are faster than traditional databases like MySQL, Oracle, MongoDB, CouchDB, etc. for one important reason that this data is stored in RAM rather than on Harddisks. Both Redis and Memcached are accessible via their REST APIs.

When it comes to Read/Write operations, Memcached and Redis performances are almost identical, both are lightning fast. Both Memcached and Redis belong to the NoSQL family of databases, and both are based on a key-value data model. Structure of information stored in these databases can be matched to the JSON documents.

Referring to the features, Redis is more feature rich database than Memcached.

Both databases have their pros and cons. In this article, we will create a simple Redis cluster on Elasticache and then access this cluster from our PHP code that is placed on an EC2 instance in the same geographical region (we use Mumbai in this example). The foremost requirement before proceeding with this tutorial is that you need to have a verified AWS account, working knowledge of AWS console, PHP and Redis. You are also required to have basic Linux command line knowledge so that you can install basic tools like Zip, Unzip, Redis CLI and PHP on the EC2 Linux Instance. Lastly, the preferred region needs to be selected from the top right corner of your AWS console. Once done, login to your AWS console to proceed with the following steps.

[Step #1: Creating Security Group]

This is the most important step in setting up your Redis cluster. For this example, we will create our own security group by the name of ‘eduonix-sg’. While creating this security group, make sure to set the following two inbound rules:

—————————————- —————————————-

First Inbound Rule

—————————————- —————————————-

Type: Custom TCP

Protocol: TCP

Port Range: 6379

Source: Anywhere

—————————————- —————————————-

Second Inbound Rule

—————————————————— ————————–

Type: SSH

Protocol: TCP

Port Range: 22

Source: Anywhere

This security group will be assigned to both the EC2 instance and Elasticache cluster. The first rule is set to make our Redis cluster accessible from within our EC2 instance. The second rule is being created to allow our EC2 instance to be accessible via SSH from our local computer. The outbound rule will be set to its default value.

Please note: – By default, Elasticache clusters are only accessible from EC2 instances. You cannot make calls to your Redis cluster from the outside. This means if you have created a Redis cluster and are trying to access it from your local computer, you won’t be able to do it. Anyhow, for development purposes you may need to access your Redis cluster from your development machine, for which you can follow this guide which explains the additional steps.

[Step #2: Creating Elasticache Instance]

While creating your new Elasticache cluster, please keep the following points in mind:

1. Cluster engine should be set to Redis.

2. You can enable cluster mode if you want to, but as this tutorial only covers the basic usage, so we keep it disabled.

3. You need to give a unique name to your Redis cluster. We have named it ‘eduonix-rc’ for this example.

4. ‘Number of replicas’ is set to None.

5. Port is set to the default i.e. 6379.

6. Node type is changed to ‘cache.t2.micro’ for this example.

7. Make sure that the ‘security group’ is set only to the one created above i.e. ‘eduonix-sg’.

8. Everything else can be left to the ‘default value’.

[Step #3 Creating EC2 Instance]

For this example, we will create a 64-bit ‘Ubuntu Server 16.04 LTS (HVM)’ instance. While creating this instance, at “Step 6: Configure Security Group”, make sure to assign the security group to the one created in the first step i.e. ‘eduonix-sg’. All other options can be set as per your preference.

[Step #4 Setting up EC2 instance to access Redis cluster]

Once the instance is launched. you need to access this instance via SSH using your ‘.pem’ file. Sample command is as follows:

1<code>$ pranav@pranav-laptop:~/Desktop$ ssh -i ./[keys.pem] ubuntu@ec2-[ip-address].ap-south-1.compute.amazonaws.com</code>

Once you are logged in to your ec2 instance, the first thing that you need to do is install the ‘redis tools’, we will use this tool to check the connection with our Redis cluster. You can install the ‘Redis tools’ with the following terminal commands:

$ sudo apt-get update

$ sudo apt-get install redis-tools

Once done, we now use the following terminal command to access our newly created Redis cluster:

$ redis-cli -h [Primary-endpoint-url-of-the-cluster] -p 6379

Using the above command, you should now enter the Redis CLI mode. Try the following two commands to check your Redis installation:

$ set name "Michael Jackson"

$ get name

If everything has been properly configured, the above commands should get and set values without any problems.

The next requirement is to install PHP. You can either install the entire LAMP Stack or just PHP CLI. For this example, we will only install PHP for this example using the following command:

$ sudo apt-get install php7.0-cli

Once done, we can check our PHP installation using the following command:-

$ php -v

The above command should print the basic PHP information on the terminal. We are now all set to access our Redis cluster from our EC2 instance using PHP.

Please note: – The following code examples will work in both CLI mode and server side mode.

[Step #5 Installing Predis library to use with our PHP code]

Redis has bindings for almost all mainstream programming languages. The complete list of PHP bindings for Redis can be found here. For this example, we will be using PHP Predislibrary. This lbrary is mature and stable and is being widely used by the PHP community. The complete list of available functionality for this library can be found here. You can directly download this library from Github and use it in your PHP code or you can use Composer package manager to install this library. In this example, we will be installing Predis using Composer. The Composer command to install Predis is as follows:

$ sudo apt-get install zip unzip

$ composer require predis/predis

Here, we are installing the official Predis pakage from Packagist. ‘Zip’ and ‘Unzip’ packages are required by Composer, so we are installing these packages before running the composer command.

[Step #6 Preparing PHP code to access Redis cluster]

We are now ready to access our Redis cluster using PHP. Please have a look at the following PHP code:

<?php # redis initialization

require __DIR__.'/vendor/autoload.php'; # including composer autoload file

# making redis connection

try{

$redis = new Predis\Client([

'scheme' => 'tcp',

'host' => '[Primary-endpoint-url-of-the-redis-cluster]',

'port' => 6379

]);

}catch(Exception $ex){

echo $ex->getMessage();

}

# working with simple string values

$redis->set("hello_world", "Hello Redis from php!");

echo $redis->get("hello_world");

?>


The above code once executed should print “Hello Redis from php!” on the screen. Make sure to replace “[Primary-endpoint-url-of-the-redis-cluster]” with the endpoint of your Redis cluster (this endpoint url can be found in your AWS Console).

[Data types supported in Redis]

Now you have your Redis cluster up and running on AWS. You can perform all supported Read/Write operations on this cluster that you would on any other Redis server. Data types that are supported by Redis are as follows:

1. Strings

2. Lists

3. Sets

4. Hashes

5. Sorted sets

6. Bitmaps and HyperLogLogs

More on these can be found at the official Redis documenation.

In the following examples, we cover the two most commonly used data types in Redis, i.e. strings and hashes. Strings can be simple strings as well as numbers. Numbers are treated as strings in Redis. Hashes are more like JSON objects or multi dimensional PHP Arrays. Both of these data types are demonstrated below.

Read / Write operations on strings

<?php # strings

$redis->set("hello_world", "Hi All from Predis!");

echo $redis->get("hello_world");

echo "\n";

$redis->set("my_age", 29);

echo $redis->get("my_age");

echo "\n";

?>

Please note: – Both of the above values i.e. (“Hi All from Predis!” and 29) are stored as strings in Redis. The above code would output:——————————————————————————————

Hi All from Predis!

29

—————————————————————————————

Read / Write operations on hashes


<?php

$redis->hmset("captain-america", [

'real name' => 'Steve Rogers',

'super power' => 'Super Human Strength',

'superhero name' => 'Captain America',

'age in years' => 120

]);

echo "Age of Steve Rogers is ".$redis->hget('captain-america', 'age in years')." years.\n";

echo "Complete Profile of Steve Rogers is:\n";

var_dump($redis->hgetall('captain-america'));

echo "\n";

?>

The output of the above code would be as follows:

——————————————————————————————

Age of Steve Rogers is 120 years.

Complete Profile of Steve Rogers is:

array(4) {

[“real name”]=>

string(12) “Steve Rogers”

[“super power”]=>

string(20) “Super Human Strength”

[“superhero name”]=>

string(15) “Captain America”

[“age in years”]=>

string(3) “120”

}

——————————————————————————————

Basically, You can perform all kinds of operations on the Redis cluster that you would on your stand alone Redis installation. This includes all supported data types as well as additional functions like incrementers and decrementers.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容