nginx{yuminstallymakegccopenssldevelpcredevelbzip2devellibxml2libxml2develcurldevellibmcryptdevellibjpeglibjpegdevellibpnglibpngdevelopensslgroupaddnginxuseraddnginxgnginxMssbinnologinmkdirpoptnginxtmpwgethttp:labs。frickle。comfilesngxcachepurge1。6。tar。gztarfxzngxcachepurge1。6。tar。gzngxcachepurge清除指定url缓存假设一个URL为http:192。168。12。133test。txt通过访问http:192。168。12。133purgetest。txt就可以清除该URL的缓存。tarzxvpfnginx1。4。4。tar。gzcdnginx1。4。4。configurehelpwith默认不加载需指定编译此参数才使用without默认加载,可用此参数禁用addmodulepath添加模块的路径addmoduleoptngxmoduleupstreamchecknginx代理状态页面ngxmoduleupstreamcheck编译前需要打对应版本补丁patchp1optnginxupstreamcheckmodulecheck1。2。6。patchaddmoduleoptngxmodulememc将请求页面数据存放在memcached中addmoduleoptngxmodulelua支持lua脚本yuminstallluadevellua。configureusernginxgroupnginxprefixusrlocalnginxwithhttpsslmodulewithhttprealipmodulewithhttpgzipstaticmodulewithhttpstubstatusmoduleaddmoduleoptngxcachepurge1。6httpclientbodytemppathoptnginxtmpclienthttpproxytemppathoptnginxtmpproxyhttpfastcgitemppathoptnginxtmpfastcgihttpuwsgitemppathoptnginxtmpuwsgihttpscgitemppathoptnginxtmpscgimakemakeinstallusrlocalnginxsbinnginxt检查Nginx配置文件但并不执行usrlocalnginxsbinnginxtcoptnginxconfnginx。conf检查Nginx配置文件usrlocalnginxsbinnginx启动nginxusrlocalnginxsbinnginxsreload重载配置usrlocalnginxsbinnginxsstop关闭nginx服务} elasticsearch{vimetcsysctl。confvm。maxmapcount262144vimetcsecuritylimits。confsoftmemlockunlimitedhardmemlockunlimitedsysctlpcurllocalhost:9200cathealth?vahrefhttps:www。q578。coml160targetblankclassinfotextkey健康a检查curllocalhost:9200catnodes?v获取集群的节点列表curllocalhost:9200catindices?v列出所有索引curl127。0。0。1:9200indexnameXDELETE删除索引curlXGEThttp:localhost:9200catshards查看分片curl127。0。0。1:9200catindices查分片同步unassignedshards没同步完成}mysql常用命令{mysql可视化工具MySQLWorkbenchmysqlcheckurootpSmysql。sockoptimizedatabasesaccount检查、修复、优化MyISAM表mysqlbinlogslaverelaybin。000001查看二进制日志mysqladminhmyhosturootpcreatedbname创建数据库flushprivileges;刷新showdatabases;显示所有数据库usedbname;打开数据库showtables;显示选中数据库中所有的表desctables;查看表结构dropdatabasename;删除数据库droptablename;删除表createdatabasename;创建数据库selectcolumnfromtable;查询showprocesslist;查看mysql进程showfullprocesslist;显示进程全的语句selectuser();查看所有用户showslavestatusG;查看主从状态showvariables;查看所有参数变量showstatus;运行状态showtablestatus查看表的引擎状态showgrantsforuser查看用户权限droptableifexistsuser表存在就删除createtableifnotexistsuser表不存在就创建selecthost,user,passwordfromuser;查询用户权限先usemysqlcreatetableka(kaidvarchar(6),qianshuint);创建表showvariableslikecharacterset;查看系统的字符集和排序方式的设定showvariablesliketimeout;查看超时相关参数deletefromuserwhereuser;删除空用户deletefromuserwhereusersssandhostlocalhost;删除用户dropuserssslocalhost;使用此方法删除用户更为靠谱ALTERTABLEmytableENGINEMyISAM;改变现有的表使用的存储引擎SHOWTABLESTATUSfromdbnamewhereNametablename;查询表引擎mysqlurootpAssh10。10。10。5eshowdatabases;shell中获取数据不带表格ss参数CREATETABLEinnodb(idint,titlechar(20))ENGINEINNODB创建表指定存储引擎的类型(MyISAM或INNODB)grantreplicationslaveon。touseridentifiedbypwd;创建主从复制用户ALTERTABLEplayerADDINDEXweekcreditfactionindex(weekcredit,faction);添加索引altertablenameaddcolumnaccountid(column)int(11)NOTNULL(column);插入字段updatehostsetmonitorstateY,hostnamexuesongwhereip192。168。1。1;更新数据selectfrominformationschema。processlistwherecommand!sleep;查看当前进程selectfromatablewherenameonANDt15ANDhostLIKE10limit1,10;多条件查询showcreatedatabaseopsdeploy;查看数据库编码showcreatetableupdatelog;查看数据库表编码alterdatabaseopsdeployCHARACTERSETutf8;修改数据库编码altertableupdatelogdefaultcharactersetutf8;修改表编码altertableupdatelogconverttocharactersetutf8;修改一张表的所有字段的编码格式自增表{createtablexuesong(idINTEGERPRIMARYKEYAUTOINCREMENT,nameCHAR(30)NOTNULL,ageinteger,sexCHAR(15));创建自增表insertintoxuesong(name,age,sex)values(s,s,s)自增插入数据}登录mysql的命令{格式:mysqlh主机地址u用户名p用户密码mysqlh110。110。110。110P3306urootpmysqlurootpSdata1mysql5datamysql。sockAdefaultcharactersetGBK}shell执行mysql命令{mysqlurootp123xuesongfile。sql针对指定库执行sql文件中的语句,好处不需要转义特殊符号,一条语句可以换行。不指定库执行时语句中需要先usemysqluusernameppasswdhdbhostPdbportAeusedbname;deletefromdatawheredate(date1);执行多条mysql命令mysqlurootpSmysql。sockeusedb;altertablegiftaddcolumnaccountidint(11)NOTNULL;flushprivileges;21grepvWarning不登陆mysql插入字段}mysql字符集相关{showvariableslikecharacter;查看数据库中设置字符集的参数charactersetclient、charactersetconnection以及charactersetresults这几个参数都是客户端的设置charactersetsystem、charactersetserver以及charactersetdatabase是指服务器端的设置。而对于这三个服务器端的参数来说的优先级是:列级字符集表级字符集charactersetdatabasecharactersetservercharactersetsystemshowglobalvariableslikechar;查看RDS实例字符集相关参数设置showglobalvariableslikecoll;查看当前会话字符序相关参数设置showcharacterset;查看实例支持的字符集showcollation;查看实例支持的字符序showcreatetabletablenameG查看表字符集设置showcreatedatabasedatabasenameG查看数据库字符集设置showcreateprocedureprocedurenameG查看存储过程字符集设置showprocedurestatusG查看存储过程字符集设置alterdatabasedbnamedefaultcharsetutf8;修改数据库的字符集createdatabasedbnamecharactersetutf8;创建数据库时指定字符集altertabletabnamedefaultcharsetutf8collateutf8generalci;修改表字符集和字符序下面三条sql分别将库dbsdq,表tt2,表tt2中的c2列修改为utf8mb4字符集alterdatabasedbsdqcharactersetutf8mb4collateutf8mb4unicodeci;usedbsdq;altertablett2charactersetutf8mb4collateutf8mb4unicodeci;altertablett2modifyc2varchar(10)charactersetutf8mb4;修改列时,当前列中的所有行都会立即转化为新的字符集;altertable会对表加元数据锁}备份数据库{mysqldumphhosturootpdefaultcharactersetutf8dbnamedbnamebackup。sql不包括库名,还原需先创建库,在usemysqldumphhosturootpdatabasedefaultcharactersetutf8dbnamedbnamebackup。sql包括库名,还原不需要创建库binmysqlhotcopyurootpmysqlhotcopy只能备份MyISAM引擎mysqldumpurootpSmysql。sockdefaultcharactersetutf8dbnametable1table2datadb。sql备份表mysqldumpurootp123ddatabasedatabase。sql备份数据库结构最小权限备份grantselectondbname。todbbackuplocalhostIdentifiedbypasswd;singletransactionInnoDB有时间戳只备份开始那一刻的数据,备份过程中的数据不会备份mysqldumphlocalhostP3306udbbackupsingletransactionppasswddatabasedbnamedbname。sqlxtrabackup备份需单独安装软件优点:速度快,压力小,可直接恢复主从复制innobackupexuserrootpassworddefaultsfiledatamysql5datamy3306。cnfsocketdatamysql5datamysql。sockslaveinfostreamtartmpdirdatadbbackuptempdatadbbackup2datadbbackupdbbackup。loggzip1datadbbackupdb50。tar。gz}还原数据库{mysqlhhosturootpdbnamedbnamebackup。sqlsource路径。sql登陆mysql后还原sql文件}赋权限{指定IP:IP本机:localhost所有IP地址:通常指定多条grantallonzabbix。touserIP;对现有账号赋予权限grantselectondatabase。touserIdentifiedbypasswd;赋予查询权限(没有用户,直接创建)grantallprivilegesondatabase。touserIPidentifiedbypasswd;赋予指定IP指定用户所有权限(不允许对当前库给其他用户赋权限)grantallprivilegesondatabase。touserlocalhostidentifiedbypasswdwithgrantoption;赋予本机指定用户所有权限(允许对当前库给其他用户赋权限)grantselect,insert,update,deleteondatabase。touseripidentifiedbypasswd;开放管理操作指令revokeallon。fromuserlocalhost;回收权限GRANTSELECT,INSERT,UPDATE,DELETE,CREATE,DROP,INDEX,ALTER,EXECUTE,CREATEROUTINE,ALTERROUTINEONstoremiscdev。TOuser192。168。}更改密码{updateusersetpasswordpassword(passwd)whereuserrootmysqladminurootpasswordxuesong}mysql忘记密码后重置{cddatamysql5datamysql5binmysqldsafeusermysqlskipgranttablesskipnetworkingusemysql;updateusersetpasswordpassword(123123)whereuserroot;}mysql主从复制失败恢复{slavestop;resetslave;changemastertomasterhost10。10。10。110,masterport3306,masteruserrepl,masterpasswordrepl,masterlogfilemasterbin。000010,masterlogpos107,masterconnectretry60;slavestart;}sql语句使用变量{usexuesong;setaconcat(my,weekday(curdate()));组合时间变量setsql:concat(CREATETABLEIFNOTEXISTS,a,(idINT(11)NOTNULL));组合sql语句selectsql;查看语句preparecreatetbfromsql;准备executecreatetb;执行}检测mysql主从复制延迟{1、在从库定时执行更新主库中的一个timeout数值2、同时取出从库中的timeout值对比判断从库与主库的延迟}死锁{showOPENTABLESwhereInuse0;查看当前锁信息showvariableslikeinnodbprintalldeadlocks;查看当前死锁参数setglobalinnodbprintalldeadlocks1;设置死锁信息保存到错误日志innodbprintalldeadlocks1conf配置}mysql慢查询{selectfrominformationschema。processlistwherecommandin(Query)andtime5G查询操作大于5S的进程开启慢查询日志{配置文件etcmy。conf〔mysqld〕logslowqueriesvarlibmysqlslowquery。log指定日志文件存放位置,可以为空,系统会给一个缺省的文件hostnameslow。loglongquerytime5记录超过的时间,默认为10s建议0。5Slogqueriesnotusingindexeslog下来没有使用索引的query,可以根据情况决定是否开启可不加loglongformat如果设置了,所有没有使用索引的查询也将被记录可不加直接修改生效showvariableslikeslow;查看慢查询状态setglobalslowquerylogON;开启慢查询日志变量可能不同,看上句查询出来的变量}mysqldumpslow慢查询日志查看{s是order的顺序,包括看了代码,主要有c,t,l,r和ac,at,al,ar,分别是按照query次数,时间,lock的时间和返回的记录数来排序,前面加了a的时倒序t是topn的意思,即为返回前面多少条的数据g后边可以写一个正则匹配模式,大小写不敏感的mysqldumpslowsct20hostslow。log访问次数最多的20个sql语句mysqldumpslowsrt20hostslow。log返回记录集最多的20个sqlmysqldumpslowt10stgleftjoinhostslow。log按照时间返回前10条里面含有左连接的sql语句showglobalstatuslikeslow;查看现在这个session有多少个慢查询showvariableslikeslow;查看慢查询日志是否开启,如果slowquerylog和logslowqueries显示为on,说明服务器的慢查询日志已经开启showvariableslikelong;查看超时阀值descselectfromweiwheretextxishizhaohuaG;扫描整张表tepe:ALL没有使用索引key:NULLcreateindextextindexonwei(text);创建索引}PerconaToolkit慢日志分析工具}mysql操作次数查询{selectfrominformationschema。globalstatus;comselectcomdeletecominsertcomupdate}}mongodb{mongo可视管理工具studio3t一、启动{不启动认证。mongodport27017forklogpathoptmongodbmongodb。loglogappenddbpathoptmongodbdata启动认证。mongodport27017forklogpathoptmongodbmongodb。loglogappenddbpathoptmongodbdataauth配置文件方式启动catoptmongodbmongodb。confport27017端口号forktrue以守护进程的方式运行,创建服务器进程authtrue开启用户认证logappendtrue日志采用追加方式logpathoptmongodbmongodb。log日志输出文件路径dbpathoptmongodbdata数据库路径shardsvrtrue设置是否分片maxConns600数据库的最大连接数。mongodfoptmongodbmongodb。conf其他参数bindip绑定IP使用mongo登录需要指定对应IPjournal开启日志功能,降低单机故障的恢复时间,取代dur参数syncdelay系统同步刷新磁盘的时间,默认60秒directoryperdb每个db单独存放目录,建议设置。与mysql独立表空间类似repairpath执行repair时的临时目录。如果没开启journal,出现异常重启,必须执行repair操作mongodb没有参数设置内存大小。使用osmmap机制缓存数据文件,在数据量不超过内存的情况下,效率非常高。数据量超过系统可用内存会影响写入性能}二、关闭{方法一:登录mongodb。mongouseadmindb。shutdownServer()方法:kill传递信号两种皆可kill2pidkill15pid}三、开启认证与用户管理{。mongo先登录useadmin切换到admin库db。addUser(root,123456)创建用户db。addUser(zhansan,pass,true)如果用户的readOnly为true那么这个用户只能读取数据,添加一个readOnly用户zhansan。mongo127。0。0。1:27017mydburootp123456再次登录,只能针对用户所在库登录虽然是超级管理员,但是admin不能直接登录其他数据库,否则报错FriNov2215:03:21。886Error:18{code:18,ok:0。0,errmsg:authfails}atsrcmongoshelldb。js:228showcollections查看链接状态再次登录使用如下命令,显示错误未经授权db。system。users。find();查看创建用户信息db。system。users。remove({user:zhansan})删除用户恢复密码只需要重启mongodb不加auth参数}四、登录{192。168。1。5:28017http登录后可查看状态mongo默认登录后打开test库mongo192。168。1。5:27017databaseName直接连接某个库不存在则创建启动认证需要指定对应库才可登录}五、查看状态{登录后执行命令查看状态db。runCommand({serverStatus:1})globalLock表示全局写入锁占用了服务器多少时间(微秒)mem包含服务器内存映射了多少数据,服务器进程的虚拟内存和常驻内存的占用情况(MB)indexCounters表示B树在磁盘检索(misses)和内存检索(hits)的次数。如果这两个比值开始上升,就要考虑添加内存了backgroudFlushing表示后台做了多少次fsync以及用了多少时间opcounters包含每种主要擦撞的次数asserts统计了断言的次数状态信息从服务器启动开始计算,如果过大就会复位,发送复位,所有计数都会复位,asserts中的roolovers值增加mongodb自带的命令。mongostatinsert每秒插入量query每秒查询量update每秒更新量delete每秒删除量locked锁定量qrqw客户端查询排队长度(读写)araw活跃客户端量(读写)conn连接数time当前时间mongostath127。0。0。1port27047authenticationDatabaseadminuzadminpKeaphh9e查看mongo状态mongotoph127。0。0。1port27047authenticationDatabaseadminuzadminpKeaphh9e查看mongo集合的统计数据}六、常用命令{db。listCommands()当前MongoDB支持的所有命令(同样可通过运行命令db。runCommand({listCommands:1})来查询所有命令)db。runCommand({buildInfo:1})返回MongoDB服务器的版本号和服务器OS的相关信息db。runCommand({collStats:tablename})返回该集合的统计信息,包括数据大小,已分配存储空间大小,索引的大小等db。runCommand({dropDatabase:1})清空当前数据库的信息,包括删除所有的集合和索引db。runCommand({isMaster:1})检查本服务器是主服务器还是从服务器db。runCommand({ping:1})检查服务器链接是否正常。即便服务器上锁,该命令也会立即返回db。runCommand({repaireDatabase:1})对当前数据库进行修复并压缩,如果数据库特别大,这个命令会非常耗时db。runCommand({serverStatus:1})查看这台服务器的管理统计信息某些命令必须在admin数据库下运行,如下两个命令:db。runCommand({renameCollection:集合名,to:集合名})对集合重命名,注意两个集合名都要是完整的集合命名空间,如foo。bar,表示数据库foo下的集合bar。db。runCommand({listDatabases:1})列出服务器上所有的数据库mongo172。20。20。1:27072mdbevaldb。tb。count();shell执行mongo语句mongohost172。20。20。1port27049rs。config();查看集群配置rs。status();查看集群节点的状态db。currentOp()获取当前正在执行的操作,可对应命令链接到ip:portdb。runCommand({logRotate:1})日志轮转rs。slaveOk()设置从库shell可读rs。addArb(172。16。10。199:27020);添加仲裁节点rs。add({host:10。2。2。2:27047,priority:0,hidden:true})添加从节点hiddentrue隐藏节点〔priority必须为0〕false不隐藏rs。remove(172。20。80。216:27047);删除节点rs。stepDown(120)主库上执行切换为从,120秒后切换回主showdbs查询dbusepost选择dbshowtables查看文档列表db。tb。drop()删除集合需要权限db。tb。remove({})删除所有数据db。tb。count()查询文档条数db。tb。find()查看文档内容db。tb。find({id:37530555})查询指定iddb。tb。find()。sort({id:1})。limit(1)查询文档最后一条db。tb。find({processed:{ne:true}})。limit(1);字段不为truedb。tb。find({processed:{eq:true}})。limit(1);字段为truedb。tb。find({processed:{exists:false}})。limit(1);字段不存在db。tb。ensureIndex({status:1},{background:true})后台加索引db。tb。getIndexes()查看索引db。tb。ensureIndex({ctype:1},{backgrounnd:true})后台添加索引1正向1反向db。tb。dropIndex({ctype:1});删除索引}七、进程控制{db。currentOp()查看活动进程db。cmd。sys。inprog。findOne()查看活动进程与上面一样opid操作进程号op操作类型(查询更新)ns命名空间,指操作的是哪个对象query如果操作类型是查询,这里将显示具体的查询内容lockType锁的类型,指明是读锁还是写锁db。killOp(opid值)结束进程db。cmd。sys。killop。findOne({op:opid值})结束进程}八、备份还原{mongodump虽然能不停机备份,但是为了获取实时数据视图的能力,使用fsync命令能在运行时复制数据目录并且不会损坏数据fsync会强制服务器将所有缓冲区的数据写入磁盘。配合lock还阻止对数据库的进一步写入,知道释放锁为止db。runCommand({fsync:1,lock:1})执行强制更新与写入锁db。cmd。sys。unlock。findOne()解锁db。currentOp()查看解锁是否正常mongoexportdtestct1ot1。dat导出JSON格式c指明导出集合d使用库mongoexportdtestct1csvfnumot1。dat导出csv格式csv指明导出csv格式f指明需要导出那些例mongoimportdtestct1filet1。datmongoimport还原JSON格式mongoimportdtestct1typecsvheaderlinefilet1。datmongoimport还原csv格式数据headerline指明不导入第一行因为第一行是列名mongodumpdtestobakmongodumpmongodump数据备份mongorestoredtestdropbakmongodumpmongorestore恢复drop恢复前先删除gzip压缩备份一个表excludeCollectionstring排除指定的集合要排除多个,使用多个mongodumphost127。0。0。1:27080ddbnamectablenameodatareportsmongodumphost127。0。0。1:27080ddbnamectablenameodatareportsreportsurootptAvaa5yNUEauthenticationDatabaseadmin恢复一个表mongorestorehost127。0。0。1:27080ddbnamectablenamedropdirdatareportstablename。bson在线拷贝一个库db。copyDatabase(fromdb,todb,fromhost,username,password,mechanism)db。copyDatabase(mate,mate,172。16。255。176:27047)}九、修复{当停电或其他故障引起不正常关闭时,会造成部分数据损坏丢失mongodrepair修复操作:启动时候加上repair修复过程:将所有文档导出,然后马上导入,忽略无效文档。完成后重建索引。时间较长,会丢弃损坏文档修复数据还能起到压缩数据库的作用db。repairDatabase()运行中的mongodb可使用repairDatabase修复当前使用的数据库{repairDatabase:1}通过驱动程序}十、python使用mongodb{easyinstallpymongopython2。7importpymongoconnectionpymongo。Connection(localhost,27017)创建连接dbconnection。testdatabase切换数据库collectiondb。testcollection获取collectiondb和collection都是延时创建的,在添加Document时才真正创建文档添加,id自动创建importdatetimepost{author:Mike,text:Myfirstblogpost!,tags:〔mongodb,python,pymongo〕,date:datetime。datetime。utcnow()}postsdb。postsposts。insert(post)ObjectId(。。。)批量插入newposts〔{author:Mike,text:Anotherpost!,tags:〔bulk,insert〕,date:datetime。datetime(2009,11,12,11,14)},{author:Eliot,title:MongoDBisfun,text:andprettyeasytoo!,date:datetime。datetime(2009,11,10,10,45)}〕posts。insert(newposts)〔ObjectId(。。。),ObjectId(。。。)〕获取所有collectiondb。collectionnames()相当于SQL的showtables获取单个文档posts。findone()查询多个文档forpostinposts。find():post加条件的查询posts。findone({author:Mike})高级查询posts。find({date:{lt:d}})。sort(author)统计数量posts。count()加索引frompymongoimportASCENDING,DESCENDINGposts。createindex(〔(date,DESCENDING),(author,ASCENDING)〕)查看查询语句的性能posts。find({date:{lt:d}})。sort(author)。explain()〔cursor〕posts。find({date:{lt:d}})。sort(author)。explain()〔nscanned〕}}