在Mac上我们使用[homebrew]包管理工具(http://brew.sh/index_zh-cn.html)来安装和管理开发工具包,例如:mysql、php、redis。只需要一个命令

1
brew install mysql

它会将所有的包安装到/usr/local/Cellar/目录下,并将文件软连接到/usr/local/

安装完成后你需要到/usr/local/Cellar/mysql/5.6.26/bin下找到mysql来启动。但是如果关掉终端,mysql服务也会随之关闭,这样就始终占据了一个终端窗口。

Mac OS 的开机启动方式

launchd 是 Mac OS 下用于初始化系统环境的关键进程,它是内核装载成功之后在OS环境下启动的第一个进程。采用这种方式来配置自启动项很简单,只需要一个plist文件,该plist文件存在的目录有:

  • LaunchDaemons ~/Library/LaunchDaemons
    用户登陆前运行 plist(程序)
  • LaunchAgents ~/Library/LaunchAgents
    用户登录后运行相应的 plist(程序)

你需要.plist文件来指定需要开机启动的程序。
以下是开机启动的.plist配置文件的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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>Label</key>
<string>org.mongodb.mongod</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/mongodb-2.0.3/bin/mongod</string>
<string>run</string>
<string>--config</string>
<string>/usr/local/mongodb-2.0.3/mongod.conf</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>WorkingDirectory</key>
<string>/usr/local/mongodb-2.0.3</string>
<key>StandardErrorPath</key>
<string>/usr/local/mongodb-2.0.3/log/error.log</string>
<key>StandardOutPath</key>
<string>/usr/local/mongodb-2.0.3/log/mongo.log</string>
</dict>
</plist>

如何编写.plist文件

brew安装的时候已经为你写好.plist文件。你只需要运行brew info mysql来查看帮助信息。

1
brew info mysql


此时终端会显示如下信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
==> Caveats
We've installed your MySQL database without a root password. To secure it run:
mysql_secure_installation
To connect run:
mysql -uroot
To have launchd start mysql at login:
ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
Then to load mysql now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
Or, if you don't want/need launchctl, you can just run:
mysql.server start

按照提示,执行ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents将mysql加入到登陆启动列表

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

或者 立即启动mysql launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

1
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

启动之后就可以关闭终端了,mysql会在后台运行。