您的位置首页  散文精选

没想到GZSANE(gzsane cc)

使用推荐的 systemd 来管理 redis 服务,做成 Service unit ,通过 systemctl 来管理。

没想到GZSANE(gzsane cc)

 

#头条创作挑战赛#写在前面分享一些安装 redis 的笔记博文内容涉及: 通过源码编译和yum 安装 redis Demo通过二进制文件和systemd运行 redis 的配置方式服务管理,配置的文件的简单介绍ansible redis 角色

ansible-role-redis 编写通过 ansible 自动化安装理解不足小伙伴帮忙指正「 傍晚时分,你坐在屋檐下,看着天慢慢地黑下去,心里寂寞而凄凉,感到自己的生命被剥夺了当时我是个年轻人,但我害怕这样生活下去,衰老下去。

在我看来,这是比死亡更可怕的事--------王小波」部署Redis服务安装包下载: wget https://download.redis.io/redis-stable.tar.gz┌──[root@vms153.liruilongs.github.io]-[~]

└─$wgethttps://download.redis.io/redis-stable.tar.gz--2022-10-0200:36:22--https://download.redis.io/redis-stable.tar.gz

.........2022-10-0200:36:24(3.64MB/s)-已保存“redis-stable.tar.gz”[3047785/3047785])解压编译安装┌──[root@vms153.liruilongs.github.io]-[~] └─$tar -xzf redis-stable.tar.gz ┌──[root@vms153.liruilongs.github.io]-[~] └─$cd redis-stable/ ┌──[root@vms153.liruilongs.github.io]-[~

/redis-stable] └─$ls 00-RELEASENOTES CONTRIBUTING.md INSTALL README.md runtest-cluster SECURITY.md tests BUGS COPYING Makefile redis.conf runtest-moduleapi sentinel.conf TLS.md CODE_OF_CONDUCT.md deps MANIFESTO runtest runtest-sentinel src utils

编译 Redis,切换到根目录,然后运行make:如果编译成功,你会在src目录中找到几个 Redis 二进制文件,包括:redis-server : Redis 服务器本身redis-cli是与 Redis 对话的命令行界面实用程序。

要在/usr/local/bin中安装这些二进制文件,请运行:make install┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]└─$make

cdsrc&&makeallwhich:nopython3in(/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)make[1]:进入目录“/root/redis-stable/src”

CCMakefile.depmake[1]:离开目录“/root/redis-stable/src”which:nopython3in(/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)

make[1]:进入目录“/root/redis-stable/src”CCadlist.o/bin/sh:cc:未找到命令make[1]:***[adlist.o]错误127make[1]:离开目录“/root/redis-stable/src”

make:***[all]错误2┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]└─$rpm-qgcc||yum-yinstallgcc没有 gcc 包,需要安装一下

┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$make && make install ........ Hint: Its a good idea to run

make test;) INSTALL redis-server INSTALL redis-benchmark INSTALL redis-cli make[1]: 离开目录“/root/redis-stable/src” ┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$

初始化配置配置服务运行参数 ./utils/install_server.sh 执行源码目录下的初始化脚本┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$./utils/install_server.sh Welcome to the redis service installer This script will

help you easily set up a running redis server This systems seems touse systemd. Please take a look at

the provided example service unit files in this directory, and adapt andinstall them. Sorry! 这里提示退出了,当前系统的引导进程使用的是

systemd所以,redis 不建议通过这样的方式初始化启动这里有两种解决办法:需要把导致退出的这个状态码注释掉,脚本就可以顺利执行,通过二进制文件启动使用推荐的 systemd 来管理 redis 服务,做成 Service unit ,通过 systemctl 来管理。

当前,作为 Service unit 之后更方便管理,这里我们分别看下二进制方式┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$vim

./utils/install_server.sh #bail if this system is managed by systemd _pid_1_exe="$(readlink -f /proc/1/exe)

"if [ "${_pid_1_exe##*/}" = systemd ] thenecho"This systems seems to use systemd."echo"Please take a look at the provided example service unit files in this directory, and adapt and install them. Sorry!"

#exit 1运行脚本,默认值即可┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$./utils/install_server.sh Welcome to the redis service installer This script will

help you easily set up a running redis server This systems seems touse systemd. Please take a look at

the provided example service unit files in this directory, and adapt andinstall them. Sorry! Please

select the redis port for this instance: [6379] Selecting default: 6379 Please select the redis config

filename [/etc/redis/6379.conf] Selected default - /etc/redis/6379.conf Please select the redis logfile

name [/var/log/redis_6379.log] Selected default - /var/log/redis_6379.log Please select the datadirectory

for this instance [/var/lib/redis/6379] Selected default - /var/lib/redis/6379 Please select the redis executable

path [/usr/local/bin/redis-server] Selected config: Port : 6379 Config file : /etc/redis/

6379.conf Logfile : /var/log/redis_6379.log Data dir : /var/lib/redis/6379 Executable : /usr/

local/bin/redis-server Cli Executable : /usr/local/bin/redis-cli Is this ok? Then press ENTER togoonor

Ctrl-C to abort. Copied /tmp/6379.conf => /etc/init.d/redis_6379 Installing service... Successfully added

to chkconfig! Successfully added to runlevels 345! Starting Redis server... Installation successful! ┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$

生成的配置信息:端口 6379主配置文件 /etc/redis/6379.conf日志文件 /var/log/redis_6379.log数据库目录 /var/lib/redis/6379服务启动程序

/usr/local/bin/redis-server命令行连接命令 /usr/local/bin/redis-cliService unit 的方式这里为了演示,我们换一台机器,下载解压安装包┌──[root@vms156.liruilongs.github.io]-[~] └─$wget

https://download.redis.io/redis-stable.tar.gz ┌──[root@vms156.liruilongs.github.io]-[~] └─$tar -xzf redis-stable.tar.gz ┌──[root@vms156.liruilongs.github.io]-[~] └─$cd redis-stable/

这里的话需要安装一个 systemd-devel 包,否则 Service 启动会报下面的错 systemd supervision requested or auto-detected, but Redis is compiled without libsystemd support!

┌──[root@vms156.liruilongs.github.io]-[~/redis-stable] └─$yum -y install gcc ┌──[root@vms156.liruilongs.github.io]

-[~/redis-stable] └─$yum -y install systemd-devel 编译移动二进制文件┌──[root@vms156.liruilongs.github.io]-[~/redis-stable] └─$make USE_SYSTEMD=

yes && make install 确认二进制文件┌──[root@vms156.liruilongs.github.io]-[/usr/local/bin]└─$ll/usr/local/bin/redis*

-rwxr-xr-x1rootroot519894410月3015:55/usr/local/bin/redis-benchmarklrwxrwxrwx1rootroot1210月3015:55/usr/local/bin/redis-check-aof

->redis-serverlrwxrwxrwx1rootroot1210月3015:55/usr/local/bin/redis-check-rdb->redis-server-rwxr-xr-x1root

root541622410月3015:55/usr/local/bin/redis-clilrwxrwxrwx1rootroot1210月3015:55/usr/local/bin/redis-sentinel

->redis-server-rwxr-xr-x1rootroot1140180010月3015:55/usr/local/bin/redis-server┌──[root@vms156.liruilongs.github.io]-[/usr/local/bin]

└─$从 安装包的里复制移动相关的单元文件和配置文件┌──[root@vms156.liruilongs.github.io]-[~/redis-stable/utils] └─$mv systemd-redis_server.service /etc/systemd/

system/redis.service ┌──[root@vms156.liruilongs.github.io]-[~/redis-stable/utils] └─$cd .. ┌──[root@vms156.liruilongs.github.io]-[~

/redis-stable] └─$mkdir -p /etc/redis/ ┌──[root@vms156.liruilongs.github.io]-[~/redis-stable] └─$cp redis.conf /etc

/redis/然后需要修改一下单元文件,这里主要修改了-启动、停止超时时间,加载的redis配置文件位置,设置为守护进程┌──[root@vms156.liruilongs.github.io]-[~/redis-stable] └─$systemctl cat redis

# /etc/systemd/system/redis.service# example systemd service unit file for redis-server## In order to use this as a template for providing a redis service in your

# environment, _at the very least_ make sure to adapt the redis configuration# file you intend to use as needed (make sure to set "supervised systemd"), and

# to set sane TimeoutStartSec and TimeoutStopSec property values in the units# "[Service]" section to fit your needs.

## Some properties, such as User= and Group=, are highly desirable for virtually# all deployments of redis, but cannot be provided in a manner that fits all

# expectable environments. Some of these properties have been commented out in# this example service unit file, but you are highly encouraged to set them to

# fit your needs.## Please refer to systemd.unit(5), systemd.service(5), and systemd.exec(5) for# more information.

[Unit] Description=Redis data structure server Documentation=https://redis.io/documentation #Before=your_application.service another_example_application.service

#AssertPathExists=/var/lib/redis Wants=network-online.target After=network-online.target [Service] ExecStart=/usr/local/bin/redis-server /etc/redis/redis.conf --supervised systemd --daemonize yes

## Alternatively, have redis-server load a configuration file:#ExecStart=/usr/local/bin/redis-server /path/to/your/redis.conf

LimitNOFILE=10032 NoNewPrivileges=yes #OOMScoreAdjust=-900#PrivateTmp=yes Type=notify TimeoutStartSec=30 TimeoutStopSec=30 UMask=0077

#User=redis#Group=redis#WorkingDirectory=/var/lib/redis [Install] WantedBy=multi-user.target 部分启动参数的意思

supervised systemd -通过写入READY=1到$NOTIFY_SOCKET发送信号systemd--daemonize no -默认情况下,Redis不作为守护进程运行如果需要,请使用。

yes注意,当daemonized时,Redis将在/var/run/Redis.pid中写入一个pid文件如果之前启动过,修改配置文件需要重新 reload 一下配置文件┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]。

└─$systemctldaemon-reload┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]└─$systemctlstartredis

┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]└─$systemctlstatusredis●redis.service-Redisdata

structureserverLoaded:loaded(/etc/systemd/system/redis.service;disabled;vendor preset:disabled)Active:

active(running)since日2022-10-3023:04:52CST;10sagoDocs:https://redis.io/documentationMain PID:15816(redis-server)

Status:"Ready to accept connections"CGroup:/system.slice/redis.service└─15816/usr/local/bin/redis-server

127.0.0.1:6379..............这两种方式我们直接使用 root 来运行的,一般生产环境,出于安全考虑,一般使用 redis 用户来运行管理redis 服务二进制文件方式查看进程和端口

┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]└─$ss-nutlp|grepredistcpLISTEN0128127.0.0.1:6379

*:*users:(("redis-server",pid=10800,fd=6))tcpLISTEN0128::1:6379:::*users:(("redis-server",pid=10800,fd=7))

┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]└─$ps-Credis-serverPIDTTYTIMECMD10800?00:00:00redis-server

┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]└─$┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]

└─$netstat-utnlp|grep:6379tcp00127.0.0.1:63790.0.0.0:*LISTEN10800/redis-servertcp600::1:6379:::*LISTEN

10800/redis-server停止 redis┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$/etc/init.d/redis_6379 stop Stopping ... Redis stopped ┌──[

root@vms153.liruilongs.github.io]-[~/redis-stable] └─$netstat -utnlp | grep :6379启动 redis┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$/etc/init.d/redis_6379

startStarting Redis server... ┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$ps -C redis-

server PID TTY TIME CMD 10842 ? 00:00:00 redis-server ┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$

Service unit的方式查看下进程端口相关信息┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]└─$ss-nutpl|grepredis

tcpLISTEN0128127.0.0.1:6379*:*users:(("redis-server",pid=15896,fd=6))tcpLISTEN0128::1:6379:::*users:(("redis-server",pid=15896,fd=7))

┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]└─$┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]

└─$cat/var/run/redis_6379.pid15816┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]└─$pgrepredis

15816设置开启自启┌──[root@vms156.liruilongs.github.io]-[~/redis-stable] └─$systemctl enable redis --now Created symlink

from /etc/systemd/system/multi-user.target.wants/redis.service to /etc/systemd/system/redis.service. ┌──[root@vms156.liruilongs.github.io]-[~/redis-stable] └─$

停止服务┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]└─$systemctlstopredis.service┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]

└─$systemctlstatusredis.service●redis.service-RedisdatastructureserverLoaded:loaded(/etc/systemd/system/redis.service;

enabled;vendor preset:disabled)Active:inactive(dead)since日2022-10-3023:35:57CST;14sagoDocs:https://redis.io/documentation

Process:15816ExecStart=/usr/local/bin/redis-server/etc/redis/redis.conf--supervisedsystemd--daemonize

yes(code=exited,status=0/SUCCESS)Main PID:15816(code=exited,status=0/SUCCESS)Status:"Saving the final RDB snapshot"

.....连接 redis 服务查看版本┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$redis-server -v Redis server v=

7.0.5 sha=00000000:0 malloc=libc bits=64 build=7b7dd95daaafae1 ┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$

命令行客户端使用┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]└─$redis-cli127.0.0.1:6379>pingPONG127.0

.0.1:6379>keys*(emptyarray)127.0.0.1:6379>┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]└─$远程连接

┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]└─$redis-cli-h192.168.26.153-p6350-aliruilongWarning:

Usingapasswordwith-aor-uoptiononthecommandlineinterfacemaynotbesafe.192.168.26.153:6350>GET*(nil)192.168

.26.153:6350>配置文件解析常用的配置设置┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]└─$cat/etc/redis/6379.conf

|grep-v^#|grep-v^$bind127.0.0.1-::1# 运行监听的IP地址port6379#端口daemonizeyes#是否守护进程pidfile/var/run/redis_6379.pid

# PID 文件位置loglevelnotice#日志级别logfile/var/log/redis_6379.log#日志位置databases16#数据库个数maxclients10000#客户端最大连接数

dir/var/lib/redis/6379# 数据库位置requirepassfoobared#连接需要的密码protected-modeyes#是否为保护模式┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]

└─$在默认配置中,Redis 6之后支持 ACL配置,感兴趣小伙伴可以了解下,原来的密码作为默认用户的密码下面为命令行的一些配置,当然也可以通过配置文件来配置192.168.26.153:6350>acl

list1)"user default on sanitize-payload #269028aedd888ab588d32aae3061d3d083d4c3d85ccdc3f4c51c5a0f8a53f4e4 ~* &* +@all"

192.168.26.153:6350>aclsetuserliruilongOK192.168.26.153:6350>acllist1)"user default on sanitize-payload #269028aedd888ab588d32aae3061d3d083d4c3d85ccdc3f4c51c5a0f8a53f4e4 ~* &* +@all"

2)"user liruilong off resetchannels -@all"192.168.26.153:6350>aclsetuserliruilongonOK192.168.26.153:6350>

aclsetuserliruilong+@allOK192.168.26.153:6350>acllist1)"user default on sanitize-payload #269028aedd888ab588d32aae3061d3d083d4c3d85ccdc3f4c51c5a0f8a53f4e4 ~* &* +@all"

2)"user liruilong on resetchannels +@all"192.168.26.153:6350>aclsetuserliruilong>liruilongOK192.168.26

.153:6350>authliruilongliruilongOK192.168.26.153:6350>acllist1)"user default on sanitize-payload #269028aedd888ab588d32aae3061d3d083d4c3d85ccdc3f4c51c5a0f8a53f4e4 ~* &* +@all"

2)"user liruilong on #269028aedd888ab588d32aae3061d3d083d4c3d85ccdc3f4c51c5a0f8a53f4e4 resetchannels +@all"

192.168.26.153:6350>外部连接redis ,需要更改监听接口,默认情况下 redis 开启了保护模式,只监听本地的回环地址,这里需要修改为网卡地址┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$/etc/init.d/redis_6379 stop Stopping ... Redis stopped ┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─

$seds/bind 127.0.0.1/bind 192.168.26.153/g /etc/redis/6379.conf | grep bind# By default, if no "bind" configuration directive is specified, Redis listens

# the "bind" configuration directive, followed by one or more IP addresses.# bind 192.168.1.100 10.0.0.1 # listens on two specific IPv4 addresses

# bind 192.168.26.153 ::1 # listens on loopback IPv4 and IPv6# bind * -::* # like the default, all available interfaces

# internet, binding to all the interfaces is dangerous and will expose the# following bind directive, that will force Redis to listen only on the

bind 192.168.26.153 -::1 # Using bind-source-addr it is possible to configure a specific address to bind

# bind-source-addr 10.0.0.1 ┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$seds/bind 127.0.0.1/bind 192.168.26.153/g

/etc/redis/6379.conf -i ┌──[root@vms153.liruilongs.github.io]-[~/redis-stable] └─$ 外网访问,建议修改默认端口 ┌──[root@vms153.liruilongs.github.io]-[~] └─$sed

s/^port 6379/port 6350/g /etc/redis/6350.conf | grep"port 6" port 6350# tls-port 6379# cluster-announce-tls-port 6379

# cluster-announce-bus-port 6380 ┌──[root@vms153.liruilongs.github.io]-[~] └─$sed s/^port 6379/port 6350/g

/etc/redis/6350.conf -i ┌──[root@vms153.liruilongs.github.io]-[~] └─$ 添加密码┌──[root@vms153.liruilongs.github.io]-[~] └─$sed

/^# requirepass/c requirepass liruilong /etc/redis/6350.conf | grep -i requirepass# If the master is password protected (using the "requirepass" configuration

# IMPORTANT NOTE: starting with Redis 6 "requirepass" is just a compatibility# The requirepass is not compatible with aclfile option and the ACL LOAD

# command, these will cause requirepass to be ignored. requirepass liruilong ┌──[root@vms153.liruilongs.github.io]-[~] └─$sed -i

/^# requirepass/c requirepass liruilong /etc/redis/6350.conf | grep -i requirepass ┌──[root@vms153.liruilongs.github.io]-[~] └─$

重启服务做简单测试,有的时候,我们直接 kill 调进程,作为守护进程, redis 的进程ID 依然存在┌──[root@vms153.liruilongs.github.io]-[~] └─$/etc/

init.d/redis_6379 start /var/run/redis_6379.pid exists, process is already running or crashed ┌──[root@

vms153.liruilongs.github.io]-[~] └─$cat /var/run/redis_6379.pid 10941 ┌──[root@vms153.liruilongs.github.io]-[~] └─$rm -rf /

var/run/redis_6379.pid 需要删除进程IP文件之后重新启动┌──[root@vms153.liruilongs.github.io]-[~] └─$/etc/init.d/redis_6379 start Starting Redis server... ┌──[

root@vms153.liruilongs.github.io]-[~] └─$/etc/init.d/redis_6379 status Redis is running (11179) ┌──[

root@vms153.liruilongs.github.io]-[~] └─$ 在156 机器上测试┌──[root@vms156.liruilongs.github.io]-[~/redis-stable]

└─$redis-cli-h192.168.26.153-p6350-aliruilongWarning:Usingapasswordwith-aor-uoptiononthecommandlineinterface

maynotbesafe.192.168.26.153:6350>GET*(nil)192.168.26.153:6350>涉及内存配置优化内存策略┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]

└─$cat-n/etc/redis/6379.conf|grep-v^$|grep-A15-m8maxmemory#从物理内存中划分多少内存给redis使用,#这里没有指定,则代表将本机的所有物理内存交给redis去使用;

1120# maxmemory #maxmemory-policy 定义当内存空间不足时,删除已存储数据的方式,#策略为 noeviction,即,即使内存使用完了,也不删除已存储的数据1149

# maxmemory-policy noeviction#当使用lru,lfu,ttl 策略时,需要指定key模板的个数,#默认值为5会产生足够好的结果10非常接近真实的LRU,但CPU成本更高3更快,但不是很准确。

1160# maxmemory-samples 5#逐出处理设计为在默认设置下运行良好#如果写入流量异常大,则可能需要增加值降低此值可能会降低延迟,但有被逐出的风险处理有效性#0=最小延迟,10=默认值,100=不考虑延迟的过程。

1168# maxmemory-eviction-tenacity 10┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]└─$内存淘汰策略maxmemory-policy

配置在内存不足的时候,删除已经存在的数据,对应的删除策略:┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]└─$cat-n/etc/redis/6379.conf

|grep-v^$|grep-A10MAXMEMORY1122# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory

1123# is reached. You can select one from the following behaviors:1124#1125# volatile-lru -> Evict using approximated LRU, only keys with an expire set.

1126# allkeys-lru -> Evict any key using approximated LRU.1127# volatile-lfu -> Evict using approximated LFU, only keys with an expire set.

1128# allkeys-lfu -> Evict any key using approximated LFU.1129# volatile-random -> Remove a random key having an expire set.

1130# allkeys-random -> Remove a random key, any key.1131# volatile-ttl -> Remove the key with the nearest expire time (minor TTL)

1132# noeviction -> Dont evict anything, just return an error on write operations.┌──[root@vms153.liruilongs.github.io]-[~/redis-stable]

└─$具体的描述volatile-lru -> 向redis中存入数据时,数据已满,则会在设置了TTL过期时间的变量中选择,删除最近最少使用的key,用于存放新的key;allkeys-lru -> 向redis中存入数据时,数据已满,则会在所有的变量中选择,删除最近最少使用的key,用于存放新的key;

volatile-lfu -> 向redis中存入数据时,数据已满,则会在设置了TTL过期时间的变量中选择,删除使用频率最少的key,用于存放新的key;allkeys-lfu -> 向redis中存入数据时,数据已满,则会在所有的变量中选择,删除使用频率最少的key,用于存放新的key;

volatile-random -> 向redis中存入数据时,数据已满,则会在设置了TTL过期时间的变量中选择,随机删除key,用于存放新的key;allkeys-random -> 向redis中存入数据时,数据已满,则会在所有的变量中选择,随机删除key,用于存放新的key;

volatile-ttl -> 向redis中存入数据时,数据已满,删除最近过期的key;noeviction -> 向redis中存入数据时,数据已满,显示报错提示;自动化部署 ansible Redis 角色编写

初始化一个角色┌──[root@vms152.liruilongs.github.io]-[~] └─$ansible-galaxy init ansible-role-redis --init-path=roles - Role ansible-role-redis was created successfully ┌──[root@vms152.liruilongs.github.io]-[~] └─$ansible-galaxy list

# /root/roles - ansible-role-redis, (unknown version) ┌──[root@vms152.liruilongs.github.io]-[~] └─$ yum 源 问题,这里安装 redis 3 的版本,主任务文件

主任务yaml文件编写┌──[root@vms152.liruilongs.github.io]-[~/roles]└─$catansible-role-redis/tasks/main.yml---# tasks file for ansible-role-redis

-name:EnsureRedisisinstalled.package:name:"{{ redis_package }}"state:presentenablerepo:"{{ redis_enablerepo | default(omit, true) }}

"-name:Createadirectoryredisdatafile:path:"{{ redis_dbdir }}"state:directorymode:0755-name:EnsureRedis

configurationdirexists.file:path:"{{ redis_conf_path | dirname }}"state:directorymode:0755-name:Ensure

Redisisconfigured.template:src:redis.conf.j2dest:"{{ redis_conf_path }}"mode:"{{ redis_conf_mode }}"notify:

restartredis-name:EnsureRedisisrunningandenabledonboot.service:name:"{{ redis_daemon }}"state:started

enabled:yes配置文件模板编写┌──[root@vms152.liruilongs.github.io]-[~/roles]└─$catansible-role-redis/templates/redis.conf.j2

# {{ ansible_managed }} # 是否守护进程daemonizeyes# Pid 文件位置pidfile/var/run/redis/{{ redis_daemon }}.pid# 端口

port{{ redis_port }}# 指定 监听的地址bind{{ redis_bind_interface }} # 指定Unix套接字的路径{%if redis_unixsocket %}unixsocket

{{ redis_unixsocket }}{%endif %} # 在客户闲置N秒后关闭连接(0表示禁用)timeout{{ redis_timeout }} # 日志级别和文件位置loglevel{{ redis_loglevel }}

logfile{{ redis_logfile }} # To enable logging to the system logger, just set syslog-enabled to yes,# and optionally update the other syslog parameters to suit your needs.

# syslog-enabled no# syslog-ident redis# syslog-facility local0 # 数据库个数databases{{ redis_databases }}

# 写入磁盘配置{%for save in redis_save %}save{{ save }}{%endfor %}rdbcompression{{ redis_rdbcompression }}

dbfilename{{ redis_dbfilename }}dir{{ redis_dbdir }} # maxclients 128 # 内存大小,淘汰策略,对应Key的模板个数{%if redis_maxmemory %}

maxmemory{{ redis_maxmemory }}maxmemory-policy{{ redis_maxmemory_policy }}maxmemory-samples{{ redis_maxmemory_samples }}

{%endif %} # 开启 AOF 持久化,持久化频率是否考虑缓存appendonly{{ redis_appendonly }}appendfsync{{ redis_appendfsync }}。

no-appendfsync-on-rewriteno # 包含的配文件{%for include in redis_includes %}include{{ include }}{%endfor %}

# 密码配置{%if redis_requirepass %}requirepass{{ redis_requirepass }}{%endif %} # 命令从命令{%for redis_disabled_command in redis_disabled_commands %}

rename-command{{ redis_disabled_command }} ""{%endfor %}#{{redis_extra_config }}┌──[root@vms152.liruilongs.github.io]-[~/roles]

└─$默认变量设置┌──[root@vms152.liruilongs.github.io]-[~/roles]└─$catansible-role-redis/defaults/main.yml---

redis_package:redisredis_daemon:redisredis_conf_path:/etc/redis.confredis_conf_mode:0644redis_enablerepo:

epelredis_port:6379redis_bind_interface:127.0.0.1redis_unixsocket:redis_timeout:300redis_loglevel:"notice"

redis_logfile:/var/log/redis/redis-server.logredis_databases:16# Set to an empty set to disable persistence (saving the DB to disk).

redis_save:-9001-30010-6010000redis_rdbcompression:"yes"redis_dbfilename:dump.rdbredis_dbdir:/var/lib/redis

redis_maxmemory:0redis_maxmemory_policy:"noeviction"redis_maxmemory_samples:5redis_appendonly:"no"redis_appendfsync:

"everysec"# Add extra include files for local configuration/overrides.redis_includes:[]# Require authentication to Redis with a password.

redis_requirepass:""# Disable certain Redis commands for security reasons.redis_disabled_commands:[]# - FLUSHDB

# - FLUSHALL# - KEYSls# - PEXPIRE# - DEL# - CONFIG# - SHUTDOWN# - BGREWRITEAOF# - BGSAVE# - SAVE

# - SPOP# - SREM# - RENAME# - DEBUGredis_extra_config:""┌──[root@vms152.liruilongs.github.io]-[~/roles]

└─$handle 处理器编写┌──[root@vms152.liruilongs.github.io]-[~/roles]└─$catansible-role-redis/handlers/main.yml

---# handlers file for ansible-role-redis-name:restartredisservice:name:"{{ redis_daemon }}"state:restarted

┌──[root@vms152.liruilongs.github.io]-[~/roles]└─$测试角色测试剧本yaml文件┌──[root@vms152.liruilongs.github.io]-[~]

└─$catredistest.yaml----hosts:localhostroles:-ansible-role-redis运行角色┌──[root@vms152.liruilongs.github.io]-[~] └─$ansible-playbook redistest.yaml PLAY [localhost]

************************************************************************************** TASK [Gathering Facts]

******************************************************************************** ok: [localhost] TASK [ansible-role-redis : Ensure Redis is installed.]

************************************************ changed: [localhost] TASK [ansible-role-redis : Create a directory redis data]

********************************************* changed: [localhost] TASK [ansible-role-redis : Ensure Redis configuration dir exists.]

************************************ ok: [localhost] TASK [ansible-role-redis : Ensure Redis is configured.]

*********************************************** changed: [localhost] TASK [ansible-role-redis : Ensure Redis is running and enabled on boot.]

****************************** changed: [localhost] RUNNING HANDLER [ansible-role-redis : restart redis]

************************************************** changed: [localhost] PLAY RECAP ********************

************************************************************************ localhost : ok=7 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

查看运行状态┌──[root@vms152.liruilongs.github.io]-[~]└─$systemctlstatusredis●redis.service-Redispersistentkey-value

databaseLoaded:loaded(/usr/lib/systemd/system/redis.service;enabled;vendor preset:disabled)Drop-In:/etc/systemd/system/redis.service.d

└─limit.confActive:active(running)since日2022-11-0623:44:47CST;6sagoProcess:86146ExecStop=/usr/libexec/redis-shutdown

(code=exited,status=0/SUCCESS)Main PID:86161(redis-server)CGroup:/system.slice/redis.service└─86161/usr/bin/redis-server

127.0.0.1:637911月0623:44:47vms152.liruilongs.github.iosystemd[1]:StoppedRedispersistentkey-valuedatabase.

11月0623:44:47vms152.liruilongs.github.iosystemd[1]:StartingRedispersistentkey-valuedata.....11月0623:44:47

vms152.liruilongs.github.iosystemd[1]:StartedRedispersistentkey-valuedatabase.Hint:Somelineswereellipsized,

use-ltoshowinfull.┌──[root@vms152.liruilongs.github.io]-[~]└─$时间关系,通过源码安装的角色这里没有完成,下面是安装的剧本编写,感兴趣小伙伴可以研究下

┌──[root@vms152.liruilongs.github.io]-[~/roles/ansible-role-redis/tasks]└─$catinstall_Compile.yaml---

# tasks file for ansible-role-redis-name:Downloadredistodir/tmpget_url:url:https://download.redis.io/redis-stable.tar.gz

dest:/tmp/mode:777force:yes-name:Extractarchiveunarchive:# 2.9 version# src: https://download.redis.io/redis-stable.tar.gz

src:/tmp/redis-stable.tar.gzdest:/tmp/# remote_src: yesremote_src:no-name:DependencyPackageInstallyum:

name:-gcc-systemd-develstate:present-name:Compileandinstallredisshell:cd /tmp/redis-stable/;make USE_SYSTEMD=yes && make install

-name:deleteredis-stable.tar.gzfile:path:"{{ item }}"state:absentloop:-/tmp/redis-stable-/tmp/redis-stable.tar.gz

博文参考https://github.com/geerlingguy/ansible-role-redishttps://redis.io/docs/https://zhuanlan.zhihu.com/p/386562883?utm_id=0。

免责声明:本站所有信息均搜集自互联网,并不代表本站观点,本站不对其真实合法性负责。如有信息侵犯了您的权益,请告知,本站将立刻处理。联系QQ:1640731186