Home Backend Development PHP Tutorial Redis的装配、使用以及php中扩展redis并实现php操作redis的一个例子

Redis的装配、使用以及php中扩展redis并实现php操作redis的一个例子

Jun 13, 2016 pm 12:23 PM
email nbsp protected quot redis

Redis的安装、使用以及php中扩展redis并实现php操作redis的一个例子

1、下载源码包redis-2.8.21.tar.gz,并将其上传到指定目录/urs/src,然后对其进行解压:

[[email protected] src]# tar -xvf redis-2.8.21.tar.gz

进入解压后的目录,并执行下面命令,指定安装目录为/urs/local/redis

[[email protected] src]# cd redis-2.8.21 

[[email protected] redis-2.8.21]# make PREFIX=/usr/local/redis install

安装redis成功后,可以在/usr/local/redis看到一个bin的目录,里面包括了以下文件:

[[email protected] ~]# cd /usr/local/redis/bin/

[[email protected] bin]# ls

redis-benchmark  redis-check-aof  redis-check-dump  redis-cli  redis-sentinel  redis-server

 

2、添加redis启动脚本到服务中:

/etc/rc.d/init.d目录,创建一个文件,名为redis(说明:/etc/rc.d/init.d/目录下的脚本在系统启动的时候某些指定脚本将被执行),然后在文件中添加如下内容:

[[email protected] ~]# vim /etc/init.d/redis

#!/bin/bash 

# Init file for redis 

# chkconfig: - 80 12 

# description: redis daemon 

# processname: redis 

# config: /etc/redis.conf 

# pidfile: /var/run/redis.pid 

source /etc/init.d/functions

BIN="/usr/local/redis/bin"

CONFIG="/etc/redis/redis.conf"

PIDFILE="/var/run/redis.pid"

### Read configuration 

[ -r "$SYSCONFIG" ] && source "$SYSCONFIG"

RETVAL=0

prog="redis-server"

desc="Redis Server"

start() {

        if [ -e $PIDFILE ];then

             echo "$desc already running...." 

             exit 1

        fi

        echo -n $"Starting $desc: " 

        daemon $BIN/$prog $CONFIG

        RETVAL=$?

        echo 

        [ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog

        return $RETVAL

}

stop() {

        echo -n $"Stop $desc: " 

        killproc $prog

        RETVAL=$?

        echo 

        [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog $PIDFILE

        return $RETVAL

}

restart() {

        stop

        start

}

case "$1" in

  start)

        start

        ;;

  stop)

        stop

        ;;

  restart)

        restart

        ;;

  condrestart)

        [ -e /var/lock/subsys/$prog ] && restart

        RETVAL=$?

        ;;

  status)

        status $prog

        RETVAL=$?

        ;;

   *)

        echo $"Usage: $0 {start|stop|restart|condrestart|status}" 

        RETVAL=1

esac

exit $RETVAL

 

将解压后的redis目录下的配置文件redis.conf拷贝到/etc/redis/redis.conf  (注意要与redis的启动脚本中的路径一致

[[email protected] ~]# mkdir /etc/redis

[[email protected] ~]# cp /usr/src/redis-2.8.21/redis.conf  /etc/redis/redis.conf

 

然后将redis添加到注册服务:

[[email protected] ~]# chkconfig --add redis 

[[email protected] ~]# chkconfig redis on

[[email protected] ~]# chkconfig --list redis

redis           0:off   1:off   2:on    3:on    4:on    5:on    6:off

重启redis

[[email protected] ~]# service redis restart

Stop Redis Server:                                         [  OK  ]

Starting Redis Server:                                     [  OK  ]

查看是否启动成功:

[[email protected] ~]# ps -ef | grep redis  

root      2984     1  0 13:40 ?        00:00:00 /usr/local/bin/redis-server 0.0.0.0:6379         

root      2989  2444  0 13:40 pts/1    00:00:00 grep redis

 

修改/etc/redis/redis.conf,设置redis进程为后台守护进程,并指定一个密码:

[[email protected] ~]# vim /etc/redis/6379.conf 

daemonize yes     //daemonize:是否以后台daemon方式运行

requirepass  20082009  //设置密码为20082009

设置完后,需要重启redis才能使设置生效:

[[email protected] ~]# service redis restart

 

修改环境变量文件,添加如下内容:

vim /etc/profile  

#set redis path

export REDIS_HOME=/usr/local/redis

export PATH=${REDIS_HOME}/bin:${PATH}

通过source /etc/profile 使其立刻生效

 

3、调用redis-cli的命令进行简单操作(注意是否启动密码验证):

[[email protected] ~]# redis-cli                

127.0.0.1:6379> ping

(error) NOAUTH Authentication required.

127.0.0.1:6379> auth 20082009   //需要输入密码

OK

127.0.0.1:6379> ping

PONG

127.0.0.1:6379> set name lebron james

(error) ERR syntax error

127.0.0.1:6379> set name "lebron james"  //有空格的字符串需要加“”

OK

127.0.0.1:6379> get name

"lebron james"

127.0.0.1:6379> set name lebronjames

OK

127.0.0.1:6379> get name

"lebronjames"

127.0.0.1:6379> 

 

4、php中扩展redis

下载php的一个扩展phpredis的源码包phpredis-2.2.4.tar.gz,将其上传到服务器指定位置,对其进行解压,然后进入解压后的目录:

tar -xvf phpredis-2.2.4.tar.gz

cd phpredis-2.2.4

phpize生成configure配置文件

[[email protected] phpredis-2.2.4]# /usr/local/php/bin/phpize 

然后执行如下命令:

[[email protected] phpredis-2.2.4]# ./configure --with-php-config=/usr/local/php/bin/php-config

[[email protected] phpredis-2.2.4]# make && make install

配置php支持phpredis,在php.ini文件添加如下内容:

vim /usr/local/php/lib/php.ini 

extension=  /usr/local/php/lib/php/extensions/no-debug-non-zts-20121212/redis.so

 

然后重启分别重启nginxphp-fpmredis

service nginx restart

service php-fpm restart

service redis restart

查看phpinfo(),显示如下,表明php扩展redis成功:


一个简单的php操作redis的例子:

<?php $redis = new Redis();   $redis->connect('127.0.0.1', '6379') or die ("Could not to connect to redis"); //或者具体主机的IP地址也行   $redis->set("test", “php handle redis");   var_dump($redis->get('test'));   echo "<br>";   $redis->del('test');   //删除赋值   var_dump($redis->get('test'));  ?>
Copy after login


输出结果:


从结果中可以看出,redis并没有起到作用,后来分析分析,由于之前在redis.conf文件中配置了密码登录redis的限制,现在只需要把redis.conf里面的 requirepass 20082009  这句注释掉即可:#requirepass 20082009,然后重启redisservice redis restart

再次执行php文件,显示如下结果,表明php操作redis成功:


Redis主从Master/Slave集群配置:

Master: 172.16.2.33   6379

Slave:172.16.2.42  63791

由于前面已经配置好了masterredis了,现在配置slave只需按照前面的步骤进行即可,简单步骤如下:

1)将redis的源码包redis-2.8.21.tar.gz通过scp 的方法远程复制到slave主机上,进行解压,进入解压后的文件,执行命令:make PREFIX=/usr/local/redis install,这样就在slave上安装了redis

2)接着修改环境变量文件:vim etc/profile,添加export REDIS_HOME=/usr/local/redis export PATH=${REDIS_HOME}/bin:${PATH},并通过source使其生效;

3)然后将master主机上的/etc/init.d/redis 复制到slave对应的目录上,另外把master主机上的/etc/redis/redis.conf文件也复制到slave主机上对应的目录上;

4)然后修改slave主机上的redis.conf,只需要将 # slaveof   修改为master对应的IPPORT即可:即修改为:slaveof 172.16.2.33 6379

5)接着将redis添加到chkconfig列表中:chkconfig --add redischkconfig redis on;然后重启redisservice redis restart

6)查看master主机上的信息:

[[email protected] ~]# redis-cli info replication

# Replication

role:master

connected_slaves:1

slave0:ip=172.16.2.42,port=63791,state=online,offset=924,lag=1

master_repl_offset:924

。。。

查看slave主机上的信息:

[[email protected] ~]# redis-cli -p 63791 info replication

# Replication

role:slave

master_host:172.16.2.33

master_port:6379

master_link_status:up

。。。

7)写同步测试(master主机上的写入数据同步到slave主机上):

Master主机上:

[[email protected] ~]# redis-cli 

127.0.0.1:6379> set name james

OK

127.0.0.1:6379> get name

"james"

Slave主机上:

[[email protected] ~]# redis-cli -p 63791

127.0.0.1:63791> get name

"james"

127.0.0.1:63791> set name "lebron james"

(error) READONLY You can't write against a read only slave. 

slave开启了只读模式,所以从将不能写入数据,可以保证数据只从主服务器同步至从服务器)

 

如果需要让slave也能写入数据,需要修改配置文件redis.conf:将slave-read-only yes 修改为slave-read-only no,然后重启redis(这样配置后可以向slave写入数据,但是不会同步到master,如下所示:)

Slave主机上:

[[email protected] ~]# redis-cli -p 63791   

127.0.0.1:63791> set name "lebron james"

OK

127.0.0.1:63791> get name

"lebron james"

Master主机上(slave主机上的数据并没有同步到master上):

[[email protected] ~]# redis-cli 

127.0.0.1:6379> get name

"james"

127.0.0.1:6379> 



版权声明:本文为博主原创文章,未经博主允许不得转载。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

How to read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to view all keys in redis How to view all keys in redis Apr 10, 2025 pm 07:15 PM

To view all keys in Redis, there are three ways: use the KEYS command to return all keys that match the specified pattern; use the SCAN command to iterate over the keys and return a set of keys; use the INFO command to get the total number of keys.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

See all articles