最後更新: 2022-06-29
介紹
Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker.
Redis keys are binary safe.
Try to stick with a schema. The colon sign ":" is a convention when naming keys.
For example: "object-type:id:field1.field2" is a good idea
It supports data structures such as
- strings(binary safe, max: 512 M),
- hashes,
- lists,
- sets,
- sorted sets with range queries,
- bitmaps,
- hyperloglogs,
- geospatial indexes with radius queries and streams.
Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence,
and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.
目錄
- Info
- Install
- Compile from source
- Test(CLI)
- System Settings
Info
port: 127.0.0.1:6379
user: redis
Check version
redis-server -v
redis-cli -v
127.0.0.1:6379> info server
# Server redis_version:6.2.7 redis_git_sha1:00000000 redis_git_dirty:0 redis_build_id:56aeeede275be948 redis_mode:standalone os:Linux 4.18.0-372.26.1.el8_6.x86_64 x86_64 ...
Install
# C7 - EPEL Ver: 3.2
yum install redis
# Redis cluster management utility
# providing cluster creation, node addition and removal, status checks, resharding, rebalancing, and other operations.
redis-trib
Compile from source
yum install jemalloc-devel lua-devel hiredis-devel
tar -xzf redis-*.tar.gz
cd redis-*
make
Troubleshoot
cc: error: ../deps/hiredis/libhiredis.a: No such file or directory cc: error: ../deps/jemalloc/lib/libjemalloc.a: No such file or directory
# solve by run
make distclean
cp -f redis-benchmark /usr/bin/redis-benchmark
cp -f redis-cli /usr/bin/redis-cli
cp -f redis-sentinel /usr/bin/redis-sentinel
cp -f redis-server /usr/bin/redis-server
cp -f redis-check-aof /usr/bin/redis-check-aof
cp -f redis-check-rdb /usr/bin/redis-check-rdb
Test(CLI)
# Start Server
redis-server
# Client
redis-cli ping
redis> set foo bar
OK
redis> get foo
"bar"
Configure
maxmemory
# When the memory limit is reached Redis will try to remove keys
# according to the eviction policy selected
maxmemory 128mb
# Checking
grep ^maxmemory /etc/redis.conf
redis-cli
config get maxmemory
maxmemory-policy
maxmemory-policy allkeys-lfu
- LRU means Least Recently Use
- LFU means Least Frequently Used
- volatile = the keys with an expire set
- allkeys = any key
Opts
allkeys-lru: Redis will remove the least recently used keys in order to make space for new keys.
allkeys-lfu: Evict any key using approximated LFU.
volatile-lru: Redis will remove the least recently used keys among keys with an expire set in order to make space for new keys.
volatile-lfu: Evict using approximated LFU among the keys with an expire set.
volatile-ttl: Remove the key with the nearest expire time (minor TTL)
allkeys-random: Redis will randomly select keys to remove in order to make space for new keys.
volatile-random: Remove a random key among the ones with an expire set.
noeviction: Redis will return an error when the maximum memory limit is reached and a new key needs to be added.
maxmemory-samples
# For default Redis will check five keys and pick the one that was used less recently
maxmemory-samples 5
redis-cli
redis-cli [ options ] [cmd [arg [arg ...]]]
OPTIONS
Connect
- -h hostname Server hostname (default: 127.0.0.1).
- -p port Server port (default: 6379).
- -s socket Server socket (overrides hostname and port).
-
-a password Password to use when connecting to the server.
建議用 environment variable: REDISCLI_AUTH
Search
# KEYS
redis-cli KEYS 'PHPREDIS_SESSION:*'
# SCAN
SCAN cursor [MATCH pattern] [COUNT count]
- --scan List all keys using the SCAN command.
- --pattern specify a SCAN pattern
Output format
--csv Output in CSV format.
--raw Use raw formatting for replies. force raw output even on the terminal(tty)
當是 terminal 時, output: "(integer) 7"
Repeat
-r repeat # Execute specified command N times.
-i <delay> # Unit: second. 0.1 = 100 ms
Run
-x # Read last argument from STDIN.
--eval file Send an EVAL command using the Lua script at file.
Example
# 將 mycounter +1, 另有 "DECR"
redis-cli INCR mycounter
# raw output to terminal(tty)
redis-cli --raw INCR mycounter
# Redis GET all Keys
KEYS *PHPREDIS_SESSION*
# 在 bash shell 時, "*" 要加 "\"
redis-cli KEYS PHPREDIS_SESSION\*
PHPREDIS_SESSION:UUID ...
# 將 mycounter +5
redis-cli -r 5 INCR mycounter
# set value by file
redis-cli -x SET mycounter < mycounter.txt
cat commands.txt | redis-cli
commands.txt
SET arg_example "This is a single argument" STRLEN arg_example
#
redis-cli LPUSH mylist a b c d
(integer) 4
redis-cli --csv LRANGE mylist 0 -1
"d","c","b","a"
#
redis-cli --scan --pattern '*:12345*'
List
LPUSH mylist a # inserts a new element on the head
LPUSH mylist b #
RPUSH mylist c # inserts a new element on the tail
LRANGE key start stop # list of elements in the specified range
0 being the first element of the list
-1 is the last element of the list
Out-of-range indexes
Out of range indexes will not produce an error. If start is larger than the end of the list, an empty list is returned.
If stop is larger than the actual end of the list, Redis will treat it like the last element of the list.
Monitoring
Status
--stat Print rolling stats about server: mem, clients, ... # printed every second
------- data ------ --------------------- load -------------------- - child - keys mem clients blocked requests connections 124 5.31M 3 0 439303 (+0) 219659 124 5.31M 3 0 439304 (+1) 219659
connections: 應負了多小個 connection
requests: 上一秒有多少個 request
Monitoring commands executed in Redis
redis-cli MONITOR # 它是不當 request 的
OK 1656476570.281821 [0 10.1.2.6:50968] "info" ...
Latency
# The stats are provided in milliseconds.
# Using this option the CLI runs a loop where the PING command is sent to the Redis instance
redis-cli --latency
min: 0, max: 4, avg: 0.25 (1113 samples)^C
By default: every 15 seconds
redis-cli --latency-history
Remote backups of RDB files
redis-cli --rdb /tmp/dump.rdb
System Settings
/etc/systemd/system/redis.service.d/limit.conf
[Service] LimitNOFILE=10240
/etc/logrotate.d/redis
/var/log/redis/*.log { weekly rotate 10 copytruncate delaycompress compress notifempty missingok }
/usr/lib/systemd/system/redis.service
[Unit] Description=Redis persistent key-value database After=network.target After=network-online.target Wants=network-online.target [Service] ExecStart=/usr/bin/redis-server /etc/redis.conf --supervised systemd ExecStop=/usr/libexec/redis-shutdown Type=notify User=redis Group=redis RuntimeDirectory=redis RuntimeDirectoryMode=0755 [Install] WantedBy=multi-user.target
PHP Session
php 建立 session
... "get" "PHPREDIS_SESSION:UUID" ... "setex" "PHPREDIS_SESSION:UUID" "28800"
之後每1 Click 都會 setx 一次.
SETX
# Set key to hold the string value and set key to timeout after a given number of seconds.
(相當於 SET EXPIRE 一句完成)
- SET mykey value
- EXPIRE mykey seconds
setex key seconds value
TTL
# Returns the remaining time to live of a key that has a timeout.
TTL KEY_NAME
Expire
Set a timeout on key
Expire KEY_NAME TIME_IN_SECONDS
Return Value
- 1, if the timeout is set for the key.
- 0, if the key does not exist or timeout could not set.
PHP
Php Package
yum install php-pecl-redis # Centos 7
Check Redis Script
test-redis.php
<?php $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Server is running: " . $redis->ping(); ?>
Session in Redis
/etc/httpd/conf.d/php.conf # Centos 7
# 原本 (file)
php_value session.save_handler "files" php_value session.save_path "/var/lib/php/mod_php/session"
# 使用 Redis