编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Mac上使用Homebrew来安装和启停Redis

wxchong 2024-07-08 23:34:54 开源技术 12 ℃ 0 评论

#Redis# 现在基本上已经是开发的标配了, 今天在学习下Redis, 发现使用Homebrew , 不仅可以安装, 还可以用来启动和停止Redis, 真是太方便了!

Redis(Remote Dictionary Server ),即远程字典服务,是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。从2010年3月15日起,Redis的开发工作由VMware主持。从2013年5月开始,Redis的开发由Pivotal赞助。


本文预览:

  • 介绍了取消Homebrew auto update的方法, 加快homebrew的响应速度
  • 介绍了plist文件
  • 介绍了launchctl的作用
  • 介绍了使用brew services start/stop redis的用法

使用Homebrew安装Redis

在Mac 平台上, 安装软件, 用Homebrew还是比较方便的

$ brew install redis

这里需要吐槽的是, 这个Homebrew 每次在安装的时候, 最开始先要更新(update) 一下, 这个速度实在是太慢了! 不知道是国内网络原因还是设计问题, 每次都得等一会, 真是忍不了!

看看在最开始Homebrew 都干了啥:

$ brew install redis                                                                                                      
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/cask).
==> New Casks
accordance                             evkey                                  miniforge                              skychart
airbuddy                               f-bar                                  mouse-fix                              slippi-dolphin
aldente                                fawkes                                 mubu                                   smultron
alipay-development-assistant           finisher-fluxx                         munkiadmin                             space-saver
around                                 finisher-micro                         mxsrvs                                 spaceman
astah-uml                              finisher-neo                           n1ghtshade                             spark-ar-studio
atemosc                                finisher-voodoo                        nault                                  spotter
atomic-wallet                          font-smoothing-adjuster                neat-reader                            start
audiogridder-plugin                    foobar2000                             nuage                                  stringz
audiogridder-server                    forticlient-vpn                        okta-advanced-server-access            superslicer
aural                                  fspy                                   operator                               swiftbar
banksiagui                             futubull                               opgg                                   tencent-docs
bleunlock                              fvim                                   osculator                              textbuddy
bluesnooze                             gather                                 oss-browser                            the-archive
bluewallet                             gdat                                   parsify                                the-unofficial-homestuck-collection
bome-network                           goldenpassport                         pathephone                             tradingview
brewlet                                google-drive                           pibar                                  trojanx
cakebrewjs                             grid                                   pictogram                              twobird
celestia                               helo                                   pika                                   ultdata
cinco                                  imdone                                 plasticscm-cloud-edition               unclack
cinderella                             imobie-m1-app-checker                  pokemon-trading-card-game-online       uniflash
circuitjs1                             infinity                               pragli                                 veepn
clicker-for-netflix                    intellidock                            prezi-video                            vine-server
clicker-for-youtube                    internxt-drive                         ptpwebcam                              vofa-plus
code-composer-studio                   jandi-statusbar                        radicle-upstream                       volanta
cog                                    jellybeansoup-netflix                  ray                                    wannianli
colorwell                              kekaexternalhelper                     raycast                                waterfox
curiosity                              kieler                                 reamp                                  webex
curseforge                             kiwi-for-gmail                         redream                                webull
daedalus-testnet                       kyokan-bob                             remnote                                wolfram-engine
deadbeef                               lightform                              rhino                                  xcodes
decloner                               lightkey                               scrapp                                 xournal-plus-plus
deskreen                               little-navmap                          sengi                                  yesplaymusic
devbook                                locationsimulator                      shearwater-cloud                       youtube-downloader
devutils                               macfuse                                signet                                 zecwallet-lite
digital                                mailtrackerblocker                     silicon                                zulufx
dnagedcom                              mathinspector                          silicon-info                           zy-player
duckstation                            megax                                  simplelink-msp432-sdk
dyalog                                 melonds                                simplelink-msp432e4-sdk
epoccam                                micro-sniff                            sitesucker-pro
==> Updated Casks
Updated 3074 casks.
==> Deleted Casks
ableton-live              evom                      insomnia-designer         mist                      racket-cs                 teamspeak-client
archi                     facebook-ios-sdk          irip                      monogame                  rhinoceros                waterfox-current
arrayfire                 fractal-bot               jeromelebel-mongohub      oni                       ringtones                 webex-teams
barxtemp                  futuniuniu                kekadefaultapp            openxcom                  ripit                     yyets
clashxr                   gfortran                  kode54-cog                pins                      scaleft
disablemonitor            gifs                      master-password           project-slippi-dolphin    softu2f
eventstore                google-hangouts           mega                      protonmail-unofficial     tagalicious

Warning: Treating redis as a formula. For the cask, use homebrew/cask/redis

难道这也是为程序员#摸鱼#提供机会吗?~~ 这么一想心情就好多了[呲牙][呲牙].

不过网上也提供了停止自动更新的方法, 在安装的时候,直接安装:

HOMEBREW_NO_AUTO_UPDATE=1 brew install redis

或者修改shell的配置:

--- Bash ---
$ vim ~/.bashrc
export HOMEBREW_NO_AUTO_UPDATE=1

--- Zsh ---
$ vim ~/.zshrc
export HOMEBREW_NO_AUTO_UPDATE=1

使用Source 来立刻更改:

$ source ~/.bashrc 
$ source ~/.zshrc

下面来安装一个iptable2mac来试试:

$ brew install iproute2mac                                   
==> Downloading https://homebrew.bintray.com/bottles/python%403.9-3.9.1_6.big_sur.bottle.tar.gz
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/48d123683fa125de9f02f7777683edda40e998f0e2dca492024c00bb
######################################################################## 100.0%
==> Downloading https://github.com/brona/iproute2mac/releases/download/v1.3.0/iproute2mac-1.3.0.tar.gz
######################################################################## 100.0%-#O#- #   #                         
######################################################################## 100.0%

看, 是不是快了很多!

配置Redis 启动选项

安装完之后, 需要简单配置一下Redis的启动:

ln -sfv /usr/local/opt/redis/*.plist ~/Library/LaunchAgents

等下, 什么是plist? 这有什么用?

看看官方的解释:

.plist是应用程序的“首选项”文件,其中保存了其首选项设置。通过丢弃然后重新启动应用程序,您摆脱了可能已损坏的旧用户设置首选项。这通常用于纠正用户可能遇到的应用程序问题。

其实说白了, plist 有点像Window的注册表,就是我们在Mac上使用软件的时候, 基本每个软件都会有一个Preference( 首选项)的菜单, 在这个菜单上可以增加一些自定义设置.

明白了plist的作用之后, 可以来看看Redis的plist 文件的内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>KeepAlive</key>
    <dict>
      <key>SuccessfulExit</key>
      <false/>
    </dict>
    <key>Label</key>
    <string>homebrew.mxcl.redis</string>
    <key>ProgramArguments</key>
    <array>
      <string>/usr/local/opt/redis/bin/redis-server</string>
      <string>/usr/local/etc/redis.conf</string>
      <string>--daemonize no</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>WorkingDirectory</key>
    <string>/usr/local/var</string>
    <key>StandardErrorPath</key>
    <string>/usr/local/var/log/redis.log</string>
    <key>StandardOutPath</key>
    <string>/usr/local/var/log/redis.log</string>
  </dict>
</plist>

这个就是一个xml文件, 放到哪里才能起作用呢? 来看命令:

$ ln -sfv /usr/local/opt/redis/*.plist ~/Library/LaunchAgents

为啥要放到~/Library/LaunchAgents这里面呢? 这就涉及到launchctl 这个工具的使用了.

launchctl 是什么呢?

launchctl是一个统一的服务管理框架,可以启动、停止和管理守护进程、应用程序、进程和脚本等。 launchctl是通过配置文件--plist文件来指定执行周期和任务的。

看明白了吧, launchctl 作用就跟crontab 差不多, 可以启动和调度别的程序, 不过launchctl需要plist 文件的配合.

plist脚本一般存放在以下目录:

  • /Library/LaunchDaemons -->系统启动之后,即使用户不登陆系统也会被执行
  • /Library/LaunchAgents -->用户登陆系统后才会被执行

更多的plist存放目录:

~/Library/LaunchAgents 由用户自己定义的任务项
/Library/LaunchAgents 由管理员为用户定义的任务项
/Library/LaunchDaemons 由管理员定义的守护进程任务项
/System/Library/LaunchAgents 由Mac OS X为用户定义的任务项
/System/Library/LaunchDaemons 由Mac OS X定义的守护进程任务项

在这里, 我们需要把redis的plist文件放到~/Library/LaunchAgents目录, 也就是

$ ln -sfv /usr/local/opt/redis/*.plist ~/Library/LaunchAgents

启动Redis

下面开始启动Redis, 也有几种方法.

最简单的方法, 还是使用Homebrew:

$ brew services start redis                                                         
==> Successfully started `redis` (label: homebrew.mxcl.redis)

Homebrew services 有什么功能? 打开help看看:

$ brew services --help                                                                
Usage: brew services [subcommand]

Manage background services with macOS' launchctl(1) daemon manager.

If sudo is passed, operate on /Library/LaunchDaemons (started at boot).
Otherwise, operate on ~/Library/LaunchAgents (started at login).

[sudo] brew services [list]:
    List all managed services for the current user (or root).

[sudo] brew services run (formula|--all):
    Run the service formula without registering to launch at login (or boot).

[sudo] brew services start (formula|--all):
    Start the service formula immediately and register it to launch at login
(or boot).

[sudo] brew services stop (formula|--all):
    Stop the service formula immediately and unregister it from launching at
login (or boot).

[sudo] brew services restart (formula|--all):
    Stop (if necessary) and start the service formula immediately and register
it to launch at login (or boot).

[sudo] brew services cleanup:
    Remove all unused services.

      --all                        Run subcommand on all services.
  -d, --debug                      Display any debugging information.
  -q, --quiet                      Make some output more quiet.
  -v, --verbose                    Make some output more verbose.
  -h, --help                       Show this message.

可见, brew service 就是结合launchctl 框架, 来实现对程序的启动和停止, 帮助文档中还提到, 如果命令行前面使用sudo, 就使用系统级目录/Library/LaunchDaemons, 否则就是当前用户级别目录~/Library/LaunchAgents.

Homebrew 用起来真香啊!

如果不用Homebrew, 那就稍微麻烦点:

$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.redis.plist

使用launchctl 停止Redis:

$ launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.redis.plist

连launchctl 也不用, 就用最原生的工具!

$ redis-server /usr/local/etc/redis.conf

本机验证Redis

Redis 运行在本机6379 端口, 可以直接使用redis-cli来查看:

$ redis-cli                                                                       
127.0.0.1:6379> ping
PONG

停止Redis:

简单的使用homebrew services 就可以:


$ brew services stop redis                                                           
Stopping `redis`... (might take a while)
==> Successfully stopped `redis` (label: homebrew.mxcl.redis)

草长莺飞, 正是学习之时!

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表