Redis的装配、使用以及php中扩展redis并实现php操作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
然后重启分别重启nginx,php-fpm和redis:
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')); ?>
输出结果:
从结果中可以看出,redis并没有起到作用,后来分析分析,由于之前在redis.conf文件中配置了密码登录redis的限制,现在只需要把redis.conf里面的 requirepass 20082009 这句注释掉即可:#requirepass 20082009,然后重启redis:service redis restart
再次执行php文件,显示如下结果,表明php操作redis成功:
Redis主从Master/Slave集群配置:
Master: 172.16.2.33 6379
Slave:172.16.2.42 63791
由于前面已经配置好了master的redis了,现在配置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
5)接着将redis添加到chkconfig列表中:chkconfig --add redis;chkconfig redis on;然后重启redis:service 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>
版权声明:本文为博主原创文章,未经博主允许不得转载。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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 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.

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.

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information
