Home php教程 PHP开发 redis installation, configuration, usage and redis php extension installation tutorial

redis installation, configuration, usage and redis php extension installation tutorial

Dec 21, 2016 pm 03:11 PM
redis

redis是一个内存数据库,比memcache支持更丰富的value类型,新浪微博就使用redis来做缓存。

redis的源码安装

wget http://download.redis.io/redis-stable.tar.gz
tar -zxvf redis-stable.tar.gz
cd redis-stable
make
make test
make install
Copy after login

make时可能会报如下错误:

zmalloc.o: In function `zmalloc_used_memory':
/root/redis-stable/src/zmalloc.c:223: undefined reference to `__sync_add_and_fetch_4'
collect2: ld returned 1 exit status
make[1]: *** [redis-server] Error 1
make[1]: Leaving directory `/root/redis-stable/src'
make: *** [all] Error 2
Copy after login

解决办法:
编辑src/.make-settings里的OPT,改为OPT=-O2 -march=i686。


make test报错:

You need tcl 8.5 or newer in order to run the Redis test
make: *** [test] Error 1
Copy after login

解决办法安装tcl

wget http://downloads.sourceforge.net/tcl/tcl8.6.0-src.tar.gz
cd tcl8.6.0/
cd unix &&
./configure --prefix=/usr \
            --mandir=/usr/share/man \
            --without-tzdata \
            $([ $(uname -m) = x86_64 ] && echo --enable-64bit) &&
make &&
sed -e "s@^\(TCL_SRC_DIR='\).*@\1/usr/include'@" \
    -e "/TCL_B/s@='\(-L\)\?.*unix@='\1/usr/lib@" \
    -i tclConfig.sh
make install &&
make install-private-headers &&
ln -v -sf tclsh8.6 /usr/bin/tclsh &&
chmod -v 755 /usr/lib/libtcl8.6.so
Copy after login

redis命令介绍


Redis 由四个可执行文件:redis-benchmark、redis-cli、redis-server、redis-stat 这四个文件,加上一个redis.conf就构成了整个redis的最终可用包。它们的作用如下:

redis-server:Redis服务器的daemon启动程序
redis-cli:Redis命令行操作工具。当然,你也可以用telnet根据其纯文本协议来操作
redis-benchmark:Redis性能测试工具,测试Redis在你的系统及你的配置下的读写性能
redis-stat:Redis状态检测工具,可以检测Redis当前状态参数及延迟状况
现在就可以启动redis了,redis只有一个启动参数,就是他的配置文件路径。

启动redis

复制源码包里的redis.conf到/etc

# cd redis-stable
# cp redis.conf /etc/redis.conf
Copy after login

编辑/etc/redis.conf ,修改daemaon no 为daemaon yes ,以守护进程方式启动进程。

# redis-server /etc/redis.conf
Copy after login

关闭redis

# redis-cli shutdown //关闭所有
关闭某个端口上的redis
# redis-cli -p 6397 shutdown //关闭6397端口的redis
Copy after login

说明:关闭以后缓存数据会自动dump到硬盘上,硬盘地址见redis.conf中的dbfilename dump.rdb


redis配置

注意,默认复制过去的redis.conf文件的daemonize参数为no,所以redis不会在后台运行,这时要测试,我们需要重新开一个终端。修改为yes则为后台运行redis。另外配置文件中规定了pid文件,log文件和数据文件的地址,如果有需要先修改,默认log信息定向到stdout.

下面是redis.conf的主要配置参数的意义:

daemonize:是否以后台daemon方式运行
pidfile:pid文件位置
port:监听的端口号
timeout:请求超时时间
loglevel:log信息级别
logfile:log文件位置
databases:开启数据库的数量
save * *:保存快照的频率,第一个*表示多长时间,第三个*表示执行多少次写操作。在一定时间内执行一定数量的写操作时,自动保存快照。可设置多个条件。
rdbcompression:是否使用压缩
dbfilename:数据快照文件名(只是文件名,不包括目录)
dir:数据快照的保存目录(这个是目录)
appendonly:是否开启appendonlylog,开启的话每次写操作会记一条log,这会提高数据抗风险能力,但影响效率。
appendfsync:appendonlylog如何同步到磁盘(三个选项,分别是每次写都强制调用fsync、每秒启用一次fsync、不调用fsync等待系统自己同步)
这时你可以打开一个终端进行测试了,配置文件中默认的监听端口是6379
Copy after login

redis开机自动启动

用这个脚本管理之前,需要先配置下面的内核参数,否则Redis脚本在重启或停止redis时,将会报错,并且不能自动在停止服务前同步数据到磁盘上:

# vi /etc/sysctl.conf
vm.overcommit_memory = 1
Copy after login

然后应用生效:

# sysctl –p
Copy after login

建立redis启动脚本:

# 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/bin" 
BIN="/usr/local/bin" 
CONFIG="/etc/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
Copy after login

然后增加服务并开机自启动:

# chmod 755 /etc/init.d/redis 
# chkconfig --add redis 
# chkconfig --level 345 redis on 
# chkconfig --list redis
Copy after login

redis php扩展安装

wget https://github.com/nicolasff/phpredis/zipball/master -O php-redis.zip
unzip php-redis.zip
cd nicolasff-phpredis-2d0f29b/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install
Copy after login

完成后redis.so被安装到

/usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/
vi /usr/local/php/lib/php.ini
Copy after login

添加

extension=redis.so
Copy after login

重启php-fpm即可。

configure时可能会遇到,添加--with-php-config参数可以解决。

configure: error: Cannot find php-config. Please use --with-php-config=PATH
./configure --with-php-config=/usr/local/php/bin/php-config
Copy after login

更多redis安装、配置、使用和redis php扩展安装教程相关文章请关注PHP中文网!


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 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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 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.

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

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 implement the underlying redis How to implement the underlying redis Apr 10, 2025 pm 07:21 PM

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

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 implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

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.

See all articles