Home Database Redis How to use redis

How to use redis

Jun 04, 2019 pm 03:49 PM
redis

This article will introduce the basic usage of redis.

How to use redis

1. Redis basic part:

redis applicable occasions

1. The operation of getting the latest N data

2. Ranking application, taking the TOP N operation

3. The expiration time needs to be set accurately Application

4. Counter application

5.Uniq operation, obtain all data deduplication values ​​for a certain period of time

6.Real-time system, anti-spam system

7.Pub/Sub to build a real-time messaging system

8.Build a queue system

9.Cache

SET operation 110,000 times per second, GET operations are 81,000 times per second, and the server configuration is as follows:

Linux 2.6, Xeon X3320 2.5Ghz.

The stackoverflow website uses Redis as a cache server.

The data will also be written to the hard disk. So the data is safe (except for sudden power outages, restarting the service will be written to the dump.rdb file)

1) Installation:

tar zxvf redis-2.6.9.tar.gz
cd redis-2.6.9
make
cd src && make install
Copy after login

2) Move the configuration file location (for ease of management)

cd /usr/local/
mkdir -p /usr/local/redis/bin
mkdir -p /usr/local/redis/etc
mv /lamp/redis-2.6.9/redis.conf /usr/local/redis/etc
cd /lamp/redis-2.6.9/src
mv mkreleasehdr.sh redis-benchmark redis-check-aof redis-check-dump redis-cli redis-server /usr/local/redis/bin
Copy after login

3) Modify the configuration file

vi /usr/local/redis/etc/redis.conf
Copy after login

Change no in daemonize no to yes [yes refers to running in the background]

4) Start/random start:

cd /usr/local/redis/bin
./redis-server /usr/local/redis/etc/redis.conf#启动redis并指定配置文件。
#vi /etc/rc.local #设置随机启动。
/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf
Copy after login

5) Check whether the startup is successful

ps -ef | grep redis
netstat -tunpl | grep 6379#查看端口是否占用。
Copy after login

6) Enter client/exit

cd /usr/local/redis/bin
./redis-cli#进入
quit#退出
Copy after login

7) Close redis

pkill redis-server#关闭
./redis-cli shutdown#关闭
Copy after login

Redis Security

The security of Redis???(by the following 4 methods)

1. Use ACL controller security.

2. Add the following line of configuration to the redis.conf configuration file to bind redis to a single interface (but it does not only accept data from this network card).

bind 127.0.0.1

3. Add a longer password to redis (no need to remember)

4. In redis The .conf configuration enables the authentication function.

5.SSL proxy

6.Disable the specified command.

Redis configuration

daemonize If you need to run in the background, change this item to yes

pidfile Configure multiple pid addresses by default in /var/run/redis.pid

bind binding ip, after setting, only accept requests from this ip

port listening port, the default is 6379

timeout Set the timeout when the client connects, in seconds

loglevel It is divided into 4 levels, debug, verbose, notice, warning

logfile Configure log file address

databases Set the number of databases, the default database is 0

save Set redis Frequency of database mirroring

rdbcompression Whether to perform compression when performing mirror backup

Dbfilename File name of the mirror backup file

Dir Database File placement path for mirror backup

Slaveof Set the database as the slave database of other databases

Masterauth Password verification required for master database connection

Requirepass Set the password required for login

Maxclients Limit the number of clients connected at the same time

Maxmemory Set the maximum memory that redis can use

Appendonly Turn on the append only mode

You can understand the following:

Appendfsync Set the frequency of synchronization of the appendonly.aof file

vm-enabled Whether to enable virtual memory support

vm-swap-file Set the swap file path of virtual memory

vm-max-memory Set the path used by redis Maximum physical memory size

vm-page-size Set the page size of virtual memory

vm-pages Set the total page number of the swap file

vm-max -threads Set the number of threads used by VM IO at the same time

Glueoutputbuf Store small output buffers together

hash-max-zipmap-entries Set the critical value of hash

Activerehashing Rehash

5 data types: string, hash, linked list, set, ordered set.

Supports: push/pop, add/remove, intersection, union, difference, and sorting.

redis<===Synchronization====>mysql

At the same time, the data will also be written to the hard disk. Therefore, the data is safe (except for sudden power outages, restarting the service will be written to the dump.rdb file)

select num#Select the library, the default is 0 library, a total of 16 libraries

auth liweijie#The password required for authorized users (the password is the password configured in redis.conf)

flushdb#Clear the database.

String (string) type:

set name lijie#Set the value of key name to lijie

get name#Get the value of name.

keys *#Query all keys.

setnx name liweijie#If the key already exists, it returns 0 and does not update to prevent overwriting.

setex haircolor 10 red #The validity period of the set key value is 10 seconds.

setrange email 6 lampbre.com#Change the value of the replacement key to lampbre.com starting from the 6th character

mset name1 Li Dawei name2 Li Xiaowei#Set the values ​​of multiple keys.

msetnxname1 Zhang San name3 Li Si# Determine whether the key exists. If it does not exist, set it. Otherwise, it will not set and return 0

mget name1 name2 name3#Get the values ​​of multiple keys at one time.

getset name1 Tom#Reset the value of the key and return the old key value.

getrange email 6 18#Intercept the value of the email key, from the characters between 6th and 18th.

incr uid#increments by 1 each time (if the uid in the key does not exist, set it and start from 0, the same below)

incrby uid 5#increases by 5 each time

incrby uid -5#Decrease by 5 each time

decr uid #Decrease by 1 each time

decrby uid 5#Decrease by 5 each time

appendname1 @ 126.com#To the value of name1, add the string @126.com

strlenname1#Return the length of the value of key name1.

Hashes (Hash) type:

hset user:001 name liweijie#Hash sets the name key value of user user:001 to liweijie

hset user :001 age 21#Similarly, add an age key value of 21

hsetnx user:001 age 22#Same as above, but check whether the key exists. Create if it does not exist.

hmset user:002 name liweijie2 age 26 sex 1#Set the values ​​of multiple keys at the same time.

hget user:001 name#Hash gets the value of the name key of user user:001.

hget user:001 age #Same as above.

hmget user:001 name age sex#Get the values ​​of multiple specified keys.

hgetall user:001#Get the values ​​of all keys.

hincrbyuser:001 age -8#Add the given value to the specified key.

hexists user:001 sex#Check whether the specified key value exists.

hlen user:001#Returns the number of keys/fields of the specified hash.

hdel user:001 sex#Delete the specified field or key value of the specified (user:001) hash.

hkeys user:003#Return all fields or key values ​​in the hash.

Lists (linked list) type and operation (stack or queue):

lpush mylist "world"#Insert string from the head

lpush mylist "hello "#ibid

lrange mylist 0 -1#Get from 0 to the last one such as [1) "hello" 2) "world"]

rpush mylist "jiejie "#Insert at the end

linsert mylist before "hello" "this is linsert" #Specify the insertion position (insert before hello).

lset mylist 0 "what"#Set and modify the value of the specified subscript.

lrem mylist 1 "hello"#Delete (1) element with the value hello. (n<0 is deleted from the tail, n=0 is deleted entirely)

ltrim mylist 1 2 #Retain the elements with subscript 1/2 in the table.

lpop mylist# Pop the beginning element and return.

rpop mylist# Pop the tail element and return.

rpoplpush mylist mylist2 #Pop from the end of mylist and insert it into the head of mylist2.

lindex mylist 0#Get the element value with table index 0.

llen mylist#Returns the number of table elements (equivalent to count($arr )).

sets (set) type and operation (friend recommendation, blog, tag function):

smembers myset#View all element values ​​in the myset set.

sadd myset "hello"#Add a value hello to the mysets collection

srem myset "hello"#Delete the element named hello in the myset collection.

spop myset #Randomly pop up and return an element in mysets.

sdiff myset2 myset3#Returns the difference between myset2 and myset3 (subject to myset2).

sdiffstore myset4 myset2 myset3#Return the difference between myset2 and myset3, and store it in myset4.

sinter myset2 myset3#Returns the intersection of myset2 and myset3.

sinterstore myset5 myset2 myset3#Return the intersection of myset2 and myset3 and store it in myset5.

sunion myset2 myset3#Find the union (remove duplication)

sunionstore myset6 myset2 myset3#Find the union and store it in myset6.

smove myset2 myset3 "three"#Move three in myset2 to myset3.

scard myset2#Returns the number of elements.

sismember myset2 "one"#Determine whether element one is in the myset2 set (equivalent to is_array()).

srandmember myset2# Randomly returns an element in the myset2 collection, but does not delete it (equivalent to array_rand()).

sorted sets (ordered set) type and operation (sorted by scores):

zadd myzset 1 "one"#Add element one to sequence 1

zadd myzset 2 "two"# Same as above.

zadd myzset 3 "two"#Equivalent to the value with an update order of 2

zrange myzset 0 -1 withscores#View all elements with sorting (default ascending order).

zrem myzset "two"#Delete two

zincrby myzset 2 "two"#Add 2 to the sequence value of two

zrank myzset "two"#Return to the set The index subscript value of the element.

zrevrank myzset two#Reverse the element and return the new subscript value.

zrevrange myzset 0 -1 withscores#Reverse in order (equivalent to descending order)

zrangebyscore myzset 1 10 withscores#Return elements in order 1-10 (can be paginated).

zcount myzset 1 10 #Return the number of elements in the order between 1-10.

zcard myzset#Returns the number of all elements in the set.

zremrangebyrank myzset 1 2#Delete elements with subscripts 1 to 2 in the set.

zremrangebyscore myzset 1 10#Delete elements from 1 to 10 in the set.

Common Redis commands

Key/value related commands.

keys * #Query all

keys user*#Query the specified

exists user:001# to determine whether it exists.

del name#Delete the specified key.

expire addr 10#设置过期时间

ttl addr#查询过期时间

select 0 #选择数据库

move age 1#将age移到1数据库。

get age #获取

persist age#移除age的过期时间。

randomkey#随机返回一个key

rename name1 name2#重命名键

type myset#返回键的类型。

ping #测试redis连接是否存活。

echo lamp#输出一个lamp

select 10#选择数据库。

quit/exit/crtl+C#退出客户端

dbsize#返回库里的键的个数。

服务器相关命令:

info#显示redis服务器的相关信息。

config get */loglevel #返回所有/指定的配置信息。

flushdb#删除当前库中的所有键/表。

flushall#删除所有数据库中的所有键/表

二、Redis高级部分:

1、Redis安全性:

1.用ACL控制器安全性。

2.给redis加上较长密码

# requirepass foobared

requirepass beijing

3.在redis.conf配置启用认证功能。

方式一:Auth beijing

方式二:./redis-cli -a beijing

4.在redis.conf配置文件增加下面这一行配置,即可把redis绑定在单个接口上(但并不是只有接受这个网卡的数据)。

bind 127.0.0.1(单台机器的时候可以配置,分布式或主从复制时最好不要配置)

5.SSL代理

6.禁用指定命令。

2、Redis主从复制:

redis只需在从服务器(slave)上配置即可:

slaveof 211.122.11.11 6379 #指定master 的ip 和端口

masterauth beijing#这是master主机的密码

Info#查看主/从服务器的状态。

3、Redis事务处理:

Redis事务很不完善。

4、Redis持久化机制:

方式一、备份数据到磁盘(快照)[ snapshotting(快照)也是默认方式]

记录操作命令[ Append-only file(缩写aof)的方式]

备份数据到磁盘(快照)[ snapshotting(快照)也是默认方式]

save 900 1 #900秒内如果超过1个key被修改,则发起快照保存
save 300 10 #300秒内容如超过10个key被修改,则发起快照保存
save 60 10000
Copy after login

方式二、记录操作命令[ Append-only file(缩写aof)的方式](较安全持久化)

appendonly yes #启用aof 持久化方式 
# appendfsync always //收到写命令就立即写入磁盘,最慢,但是保证完全的持久化 
appendfsync everysec //每秒钟写入磁盘一次,在性能和持久化方面做了很好的折中
Copy after login

The above is the detailed content of How to use redis. For more information, please follow other related articles on the PHP Chinese website!

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