首页 Redis教程Redis安装及使用

Redis经典入门教程

Redis实战案例:一键编译安装Redis脚本

运维派隶属马哥教育旗下专业运维社区,是国内成立最早的IT运维技术社区,欢迎关注公众号:yunweipai
领取学习更多免费Linux云计算、Python、Docker、K8s教程关注公众号:马哥linux运维

Redis安装及使用

官方下载地址:http://download.redis.io/releases/

yum安装redis

在centos系统上需要安装epel源

查看yum仓库redis版本
[root@centos8 ~]#dnf info redis
Name         : redis
Version      : 5.0.3
Release      : 1.module_el8.0.0+6+ab019c03
Architecture : x86_64
Size         : 927 k
Source       : redis-5.0.3-1.module_el8.0.0+6+ab019c03.src.rpm
Repository   : AppStream
Summary      : A persistent key-value database
URL          : http://redis.io
License      : BSD and MIT
Description  : Redis is an advanced key-value store. It is often referred to as a data
             : structure server since keys can contain strings, hashes, lists, sets and
             : sorted sets.
             : 
             : You can run atomic operations on these types, like appending to a string;
             : incrementing the value in a hash; pushing to a list; computing set
             : intersection, union and difference; or getting the member with highest
             : ranking in a sorted set.
             : 
             : In order to achieve its outstanding performance, Redis works with an
             : in-memory dataset. Depending on your use case, you can persist it either
             : by dumping the dataset to disk every once in a while, or by appending
             : each command to a log.
             : 
             : Redis also supports trivial-to-setup master-slave replication, with very
             : fast non-blocking first synchronization, auto-reconnection on net split
             : and so forth.
             : 
             : Other features include Transactions, Pub/Sub, Lua scripting, Keys with a
             : limited time-to-live, and configuration settings to make Redis behave like
             : a cache.
             : 
             : You can use Redis from most programming languages also.

[root@centos8 ~]#

[root@centos7 ~]#yum info redis
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: 
Available Packages
Name        : redis
Arch        : x86_64
Version     : 3.2.12
Release     : 2.el7
Size        : 544 k
Repo        : epel/7/x86_64
Summary     : A persistent key-value database
URL         : http://redis.io
License     : BSD
Description : Redis is an advanced key-value store. It is often referred to as a data
            : structure server since keys can contain strings, hashes, lists, sets and
            : sorted sets.
            : 
            : You can run atomic operations on these types, like appending to a string;
            : incrementing the value in a hash; pushing to a list; computing set
            : intersection, union and difference; or getting the member with highest
            : ranking in a sorted set.
            : 
            : In order to achieve its outstanding performance, Redis works with an
            : in-memory dataset. Depending on your use case, you can persist it either
            : by dumping the dataset to disk every once in a while, or by appending
            : each command to a log.
            : 
            : Redis also supports trivial-to-setup master-slave replication, with very
            : fast non-blocking first synchronization, auto-reconnection on net split
            : and so forth.
            : 
            : Other features include Transactions, Pub/Sub, Lua scripting, Keys with a
            : limited time-to-live, and configuration settings to make Redis behave like
            : a cache.
            : 
            : You can use Redis from most programming languages also.
yum安装redis
[root@centos8 ~]#dnf -y install redis
[root@centos8 ~]#systemctl start redis
[root@centos8 ~]#ss -ntl
[root@centos8 ~]#ss -tnl
State        Recv-Q        Send-Q        Local Address:Port            Peer Address:Port 
LISTEN       0             128                 0.0.0.0:22                   0.0.0.0:*     
LISTEN       0             128               127.0.0.1:6379                 0.0.0.0:*     
LISTEN       0             128                    [::]:22                      [::]:*     
[root@centos8 ~]#redis-cli 
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> info 
# Server
redis_version:5.0.3
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:8c0bf22bfba82c8f
redis_mode:standalone
os:Linux 4.18.0-147.el8.x86_64 x86_64
编译安装redis

下载当前最新release版本redis 源码包:http://download.redis.io/releases/

Redis安装及使用插图

编译安装命令

官方的安装命令:
https://redis.io/download

#安装依赖包
[root@centos7 ~]#yum -y install gcc jemalloc-devel
[root@centos7 ~]#wget http://download.redis.io/releases/redis-5.0.7.tar.gz
[root@centos7 ~]#tar xvf redis-5.0.7.tar.gz
[root@centos7 ~]#cd redis-5.0.7/
[root@centos7 redis-5.0.7]#make PREFIX=/apps/redis install #指定redis安装目录
[root@centos7 ~]#echo 'PATH=/apps/redis/bin:$PATH' > /etc/profile.d/redis.sh
[root@centos7 ~]#. /etc/profile.d/redis.sh
[root@centos7 ~]#tree /apps/redis/
/apps/redis/
└── bin
    ├── redis-benchmark
    ├── redis-check-aof
    ├── redis-check-rdb
    ├── redis-cli
    ├── redis-sentinel -> redis-server
    └── redis-server

1 directory, 6 files
[root@centos7 ~]#mkdir /apps/redis/{etc,logs,data,run} #创建配置文件、日志、数据等目录
[root@centos7 redis-5.0.7]#cp redis.conf /apps/redis/etc/
前台启动redis
[root@centos7 ~]#redis-server  /apps/redis/etc/redis.conf 
27569:C 16 Feb 2020 21:18:20.412 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
27569:C 16 Feb 2020 21:18:20.412 # Redis version=5.0.7, bits=64, commit=00000000, modified=0, pid=27569, just started
27569:C 16 Feb 2020 21:18:20.412 # Configuration loaded
27569:M 16 Feb 2020 21:18:20.413 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._                                                  
           _.-``__ ''-._                                             
      _.-`    .  `_.  ''-._           Redis 5.0.7 (00000000/0) 64 bit
  .-` .-`.  ``\/    _.,_ ''-._                                   
 (    '      ,       .-  | ,    )     Running in standalone mode
 |-._-...- __...-.-._|' _.-'|     Port: 6379
 |    -._   ._    /     _.-'    |     PID: 27569
  -._    -._  `-./  _.-'    _.-'                                   
 |-._-._    `-.__.-'    _.-'_.-'|                                  
 |    -._-._        _.-'_.-'    |           http://redis.io        
  -._    -._`-.__.-'_.-'    _.-'                                   
 |-._-._    `-.__.-'    _.-'_.-'|                                  
 |    -._-._        _.-'_.-'    |                                  
  -._    -._`-.__.-'_.-'    _.-'                                   
      -._    -.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

27569:M 16 Feb 2020 21:18:20.414 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
27569:M 16 Feb 2020 21:18:20.414 # Server initialized
27569:M 16 Feb 2020 21:18:20.414 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
27569:M 16 Feb 2020 21:18:20.414 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
27569:M 16 Feb 2020 21:18:20.414 * Ready to accept connections

[root@centos7 ~]#ss -ntl
State      Recv-Q Send-Q          Local Address:Port            Peer Address:Port         LISTEN     0      100                 127.0.0.1:25                         *:*           
LISTEN     0      128                 127.0.0.1:6379                       *:*           
LISTEN     0      128                         *:22                         *:*           
LISTEN     0      100                     [::1]:25                      [::]:*           
LISTEN     0      128                      [::]:22                      [::]:* 
解决当前的警告提示

:tcp-backlog

WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
backlog参数控制的是三次握手的时候server端收到client ack确认号之后的队列值,即全连接队列

vim /etc/sysctl.conf
net.core.somaxconn = 1024

:vm.overcommit_memory

WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add ‘vm.overcommit_memory = 1’ to /etc/sysctl.conf and then reboot or run the command ‘sysctl vm.overcommit_memory=1’ for this to take effect.

0、表示内核将检查是否有足够的可用内存供应用进程使用;如果有足够的可用内存,内存申请允许;否则,内存
申请失败,并把错误返回给应用进程。

1、表示内核允许分配所有的物理内存,而不管当前的内存状态如何

2、表示内核允许分配超过所有物理内存和交换空间总和的内存

vim /etc/sysctl.conf
vm.overcommit_memory = 1

:transparent hugepage

WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command ‘echo never > /sys/kernel/mm/transparent_hugepage/enabled’ as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.

警告:您在内核中启用了透明大页面(THP)支持。 这将在Redis中造成延迟和内存使用问题。 要解决此问题,请以根用户身份运行命令“echo never> / sys / kernel / mm / transparent_hugepage / enabled”,并将其添加到您的/etc/rc.local中,以便在重启后保留设置。 禁用THP后,必须重新启动Redis。

[root@centos7 ~]#echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.d/rc.local 
[root@centos7 ~]#cat /etc/rc.d/rc.local
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local
echo never > /sys/kernel/mm/transparent_hugepage/enabled
[root@centos7 ~]#chmod +x /etc/rc.d/rc.local

:再次启动redis:
将以上配置同步到其他redis 服务器。

[root@centos7 ~]#redis-server  /apps/redis/etc/redis.conf 
27646:C 16 Feb 2020 21:26:52.690 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
27646:C 16 Feb 2020 21:26:52.690 # Redis version=5.0.7, bits=64, commit=00000000, modified=0, pid=27646, just started
27646:C 16 Feb 2020 21:26:52.690 # Configuration loaded
27646:M 16 Feb 2020 21:26:52.690 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._                                                  
           _.-``__ ''-._                                             
      _.-`    .  `_.  ''-._           Redis 5.0.7 (00000000/0) 64 bit
  .-` .-`.  ``\/    _.,_ ''-._                                   
 (    '      ,       .-  | ,    )     Running in standalone mode
 |-._-...- __...-.-._|' _.-'|     Port: 6379
 |    -._   ._    /     _.-'    |     PID: 27646
  -._    -._  `-./  _.-'    _.-'                                   
 |-._-._    `-.__.-'    _.-'_.-'|                                  
 |    -._-._        _.-'_.-'    |           http://redis.io        
  -._    -._`-.__.-'_.-'    _.-'                                   
 |-._-._    `-.__.-'    _.-'_.-'|                                  
 |    -._-._        _.-'_.-'    |                                  
  -._    -._`-.__.-'_.-'    _.-'                                   
      -._    -.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

27646:M 16 Feb 2020 21:26:52.691 # Server initialized
27646:M 16 Feb 2020 21:26:52.692 * DB loaded from disk: 0.000 seconds
27646:M 16 Feb 2020 21:26:52.692 * Ready to accept connections
创建redis 用户和数据目录
[root@centos7 ~]#useradd -r -s /sbin/nologin redis
[root@centos7 ~]#chown redis.redis /apps/redis/ -R #注意目录权限
编辑redis服务启动文件
#复制CentOS8安装生成的redis.service文件,进行修改
[root@centos7 ~]#scp 10.0.0.8:/lib/systemd/system/redis.service /lib/systemd/system/
[root@centos7 ~]#vim /usr/lib/systemd/system/redis.service
[root@centos7 ~]#cat  /usr/lib/systemd/system/redis.service
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
ExecStart=/apps/redis/bin/redis-server /apps/redis/etc/redis.conf --supervised systemd
ExecStop=/bin/kill -s QUIT $MAINPID
Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755

[Install]
WantedBy=multi-user.target
验证redis 启动
[root@centos7 ~]#systemctl daemon-reload 
[root@centos7 ~]#systemctl start redis
[root@centos7 ~]#systemctl status redis
● redis.service - Redis persistent key-value database
   Loaded: loaded (/usr/lib/systemd/system/redis.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2020-02-16 23:08:08 CST; 2s ago
  Process: 1667 ExecStop=/bin/kill -s QUIT $MAINPID (code=exited, status=0/SUCCESS)
 Main PID: 1669 (redis-server)
   CGroup: /system.slice/redis.service
           └─1669 /apps/redis/bin/redis-server 127.0.0.1:6379

Feb 16 23:08:08 centos7.wangxiaochun.com redis-server[1669]: |-._-._    `-.__.-'    _.-'_.-'|
Feb 16 23:08:08 centos7.wangxiaochun.com redis-server[1669]: |    -._-._        _.-'_.-'    |
Feb 16 23:08:08 centos7.wangxiaochun.com redis-server[1669]: -._    -._`-.__.-'_.-'    _.-'
Feb 16 23:08:08 centos7.wangxiaochun.com redis-server[1669]: -._    -.__.-'    _.-'
Feb 16 23:08:08 centos7.wangxiaochun.com redis-server[1669]: `-._        _.-'
Feb 16 23:08:08 centos7.wangxiaochun.com redis-server[1669]: `-.__.-'
Feb 16 23:08:08 centos7.wangxiaochun.com redis-server[1669]: 1669:M 16 Feb 2020 23:08:08.931 # Server ini...ed
Feb 16 23:08:08 centos7.wangxiaochun.com redis-server[1669]: 1669:M 16 Feb 2020 23:08:08.931 * DB loaded ...ds
Feb 16 23:08:08 centos7.wangxiaochun.com redis-server[1669]: 1669:M 16 Feb 2020 23:08:08.931 * Ready to a...ns
Feb 16 23:08:08 centos7.wangxiaochun.com systemd[1]: Started Redis persistent key-value database.
Hint: Some lines were ellipsized, use -l to show in full.
[root@centos7 ~]#ss -ntl
State      Recv-Q Send-Q      Local Address:Port               Peer Address:Port              
LISTEN     0      100             127.0.0.1:25                            *:*                  
LISTEN     0      511             127.0.0.1:6379                          *:*                  
LISTEN     0      128                     *:22                            *:*                  
LISTEN     0      100                 [::1]:25                         [::]:*                  
LISTEN     0      128                  [::]:22                         [::]:*  

[root@centos7 ~]#redis-cli 
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> info
# Server
redis_version:5.0.7
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:673d8c0ee1a8872
redis_mode:standalone
os:Linux 3.10.0-1062.el7.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:4.8.5
process_id:1669
run_id:5e0420e92e35ad1d740e9431bc655bfd0044a5d1
tcp_port:6379
uptime_in_seconds:140
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:4807524
executable:/apps/redis/bin/redis-server
config_file:/apps/redis/etc/redis.conf

# Clients
connected_clients:1
client_recent_max_input_buffer:2
client_recent_max_output_buffer:0
blocked_clients:0

# Memory
used_memory:575792
used_memory_human:562.30K
used_memory_rss:3506176
used_memory_rss_human:3.34M
used_memory_peak:575792
used_memory_peak_human:562.30K
used_memory_peak_perc:100.18%
used_memory_overhead:562590
used_memory_startup:512896
used_memory_dataset:13202
used_memory_dataset_perc:20.99%
allocator_allocated:1201392
allocator_active:1531904
allocator_resident:8310784
total_system_memory:1019645952
total_system_memory_human:972.41M
used_memory_lua:37888
used_memory_lua_human:37.00K
used_memory_scripts:0
used_memory_scripts_human:0B
number_of_cached_scripts:0
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
allocator_frag_ratio:1.28
allocator_frag_bytes:330512
allocator_rss_ratio:5.43
allocator_rss_bytes:6778880
rss_overhead_ratio:0.42
rss_overhead_bytes:-4804608
mem_fragmentation_ratio:6.57
mem_fragmentation_bytes:2972384
mem_not_counted_for_evict:0
mem_replication_backlog:0
mem_clients_slaves:0
mem_clients_normal:49694
mem_aof_buffer:0
mem_allocator:jemalloc-5.1.0
active_defrag_running:0
lazyfree_pending_objects:0

# Persistence
loading:0
rdb_changes_since_last_save:0
rdb_bgsave_in_progress:0
rdb_last_save_time:1581865688
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:-1
rdb_current_bgsave_time_sec:-1
rdb_last_cow_size:0
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_last_write_status:ok
aof_last_cow_size:0

# Stats
total_connections_received:1
total_commands_processed:2
instantaneous_ops_per_sec:0
total_net_input_bytes:45
total_net_output_bytes:11475
instantaneous_input_kbps:0.00
instantaneous_output_kbps:0.00
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:0
expired_stale_perc:0.00
expired_time_cap_reached_count:0
evicted_keys:0
keyspace_hits:0
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:0
migrate_cached_sockets:0
slave_expires_tracked_keys:0
active_defrag_hits:0
active_defrag_misses:0
active_defrag_key_hits:0
active_defrag_key_misses:0

# Replication
role:master
connected_slaves:0
master_replid:f7228f0b6203183004fae8db00568f9f73422dc4
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0

# CPU
used_cpu_sys:0.132821
used_cpu_user:0.124317
used_cpu_sys_children:0.000000
used_cpu_user_children:0.000000

# Cluster
cluster_enabled:0

# Keyspace
127.0.0.1:6379> exit
[root@centos7 ~]#
使用客户端连接redis
[root@centos7 ~]#/apps/redis/bin/redis-cli -h IP/HOSTNAME -p PORT -a PASSWORD
创建命令软连接
[root@centos7 ~]#ln -sv /apps/redis/bin/redis-* /usr/bin/
‘/usr/bin/redis-benchmark’ -> ‘/apps/redis/bin/redis-benchmark’
‘/usr/bin/redis-check-aof’ -> ‘/apps/redis/bin/redis-check-aof’
‘/usr/bin/redis-check-rdb’ -> ‘/apps/redis/bin/redis-check-rdb’
‘/usr/bin/redis-cli’ -> ‘/apps/redis/bin/redis-cli’
‘/usr/bin/redis-sentinel’ -> ‘/apps/redis/bin/redis-sentinel’
‘/usr/bin/redis-server’ -> ‘/apps/redis/bin/redis-server’
编译安装后的命令
[root@centos7 ~]#ll /apps/redis/bin/
total 32772
-rwxr-xr-x 1 root root 4366792 Feb 16 21:12 redis-benchmark #redis性能测试工具
-rwxr-xr-x 1 root root 8125184 Feb 16 21:12 redis-check-aof #AOF文件检查工具
-rwxr-xr-x 1 root root 8125184 Feb 16 21:12 redis-check-rdb #RDB文件检查工具
-rwxr-xr-x 1 root root 4807856 Feb 16 21:12 redis-cli       #客户端工具
lrwxrwxrwx 1 root root      12 Feb 16 21:12 redis-sentinel -> redis-server #哨兵,软连
接到server
-rwxr-xr-x 1 root root 8125184 Feb 16 21:12 redis-server #redis 服务启动命令

本文链接:http://www.yunweipai.com/35483.html

Redis经典入门教程

Redis实战案例:一键编译安装Redis脚本

网友评论comments

发表评论

电子邮件地址不会被公开。

暂无评论

Copyright © 2012-2021 YUNWEIPAI.COM - 运维派 京ICP备16064699号-6
扫二维码
扫二维码
返回顶部