




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
MySQLMySQL主講:馬永亮(馬哥QQ群客服QQ:2813150558,MySQLStorageMySQLStorageBackupandCachingandMySQLArchitactureMySQLArchitactureandStorageEngines主講:馬永亮(馬哥QQ群客服QQ:2813150558,ThetopmostlayercontainsThetopmostlayercontainstheservicesthataren’tuniquetoServicesmostnetwork-basedclient/servertoolsorserversneed:connectionhandling,authentication,security,andsoThesecondMuchofMySQL’sbrainsarehere,includingthecodeforqueryparsing,analysis,optimization,caching,andallthebuilt-infunctions(e.g.,dates,times,math,andencryption)Anyfunctionalityprovidedacrossstorageengineslivesatthislevel:storedprocedures,triggers,andviews,forexampleThethirdlayercontainsthestorageTheyareresponsibleforstoringandretrievingalldatastored“in”MySQLthe EachEachclientconnectiongetsitsownthreadwithintheserverTheconnection’squeriesexecutewithinthatsinglethread,whichinturnresidesononecoreorCPUTheservercachesthreads,sotheydon’tneedtobecreatedanddestroyedforeachnewconnectionWhenclients(applications)connecttotheMySQLserver,theserverneedstoauthenticatethemAuthenticationisbasedonusername,originatinghost,andX.509certificatescanalsobeusedacrossanSecureSocketsLayer(SSL)connectionOnceaclienthasconnected,theserververifieswhethertheclienthasprivilegesforeachqueryitissuesMySQLMySQLparsesqueriestocreateaninternalstructure(theparsetree),andthenappliesavarietyofoptimizations,suchasrewritingthedeterminingtheorderinwhichitwillreadchoosingwhichindexestoYoucanpasshintstotheoptimizerthroughspecialkeywordsinthequery,affectingitsdecision-makingYoucanalsoasktheservertoexplainvariousaspectsofoptimizationBeforeevenparsingthequery,though,theserverconsultsBeforeevenparsingthequery,though,theserverconsultsthequerycache,whichcanstoreonlySELECTstatements,alongwiththeirresultsetsIfanyoneissuesaquerythat’sidenticaltoonealreadyinthecache,theserverdoesn’tneedtoparse,optimize,orexecutethequeryatall—itcansimplypassbackthestoredresultsetTheoptimizerdoesnotreallycarewhatstorageengineaparticulartableuses,butthestorageenginedoesaffecthowtheserveroptimizesqueryAnytimeAnytimemorethanonequeryneedstochangedataatthesametime,theproblemofconcurrencycontrolMySQLhastodothisattwolevels:theserverlevelandthestorageenginelevelLikeemailboxonUnixTheThesolutiontothisclassicproblemofconcurrencycontrolisrathersimpleSystemsthatdealwithconcurrentread/writeaccesstypicallyimplementalockingsystemthatconsistsoftwolocktypesTheselocksareusuallyknownassharedlocksandexclusivelocks,orreadlocksandwritelocksOneOnewaytoimprovetheconcurrencyofasharedresourceistobemoreselectiveaboutwhatyoulockRatherthanlockingtheentireresource,lockonlythepartthatcontainsthedatayouneedtochangeTheproblemislocksconsumeEverylockoperation—gettingalock,checkingtoseewhetheralockisfree,releasingalock,andsoon—hasoverheadAlockingstrategyisacompromisebetweenlockoverheadanddatasafety,andthatcompromiseaffectsperformanceLockmanagementisaveryimportantdecisioninstorageenginedesign;fixingthegranularityatacertainlevelcangivebetterperformanceforcertainuses,yetmakethatenginelesssuitedforotherpurposesTheThemostbasiclockingstrategyavailableinMySQL,andtheonewiththelowestoverhead,istablelocksTablelockshavevariationsforgoodperformanceinspecificsituationsForexample,READLOCALtablelocksallowsometypesofconcurrentwriteoperationsWritelocksalsohaveahigherprioritythanreadTheThelockingstylethatoffersthegreatestconcurrency(andcarriesthegreatestoverhead)istheuseofrowRow-levellocking,asthisstrategyiscommonlyknown,isavailableintheInnoDBandFalconstorageengines,amongothersRowlocksareimplementedinthestorageengine,nottheserverAAtransactionisagroupofSQLqueriesthataretreatedatomically,asasingleunitofworkTransactionsaren’tenoughunlessthesystempassestheACIDtestAtransactionmustfunctionasasingleindivisibleunitofworksothattheentiretransactioniseitherappliedorrolledbackThedatabaseshouldalwaysmovefromoneconsistentstatetothenextTheresultsofatransactionareusuallyinvisibletoothertransactionsuntilthetransactioniscompleteOncecommitted,atransaction’schangesareTheSQLstandarddefinesfourisolationlevels,withspecificrulesTheSQLstandarddefinesfourisolationlevels,withspecificrulesforwhichchangesareandaren’tvisibleinsideandoutsideaREADTransactionscanviewtheresultsofuncommittedREADAtransactionwillseeonlythosechangesmadebytransactionsthatwerealreadycommittedwhenitbegan,anditschangeswon’tbevisibletoothersuntilithascommittedREPEATABLEItguaranteesthatanyrowsatransactionreadswill“l(fā)ookthesame”insubsequentreadswithinthesametransaction,butintheoryitstillallowsanothertrickyproblem:Solvesthephantomreadproblembyforcingtransactionstobeorderedsothattheycan’tpossiblyconflictuser-defineduser-definedpointsthatcanbeusedtomarksubstageswithinatransactionSavepointswithinatransactionaresetwiththeSAVEPOINTcommand,whichacceptsauser-definedTheROLLBACKTOSAVEPOINTcommandcanthenbeusedtorollanin-progresstransactionbacktothenamedsavepoint,reversingallchangesmadeaftertheMySQLstillenablesuserstoimplementaprimitiveformMySQLstillenablesuserstoimplementaprimitiveformoftransactionsthroughtheuseoftablelocksTablePageAlockappliedtoaportionofatableknownasaBDB(BerkeleyDB)tablesuselevellockingon8-KBRowAdeadlockiswhentwoormoretransactionsaremutuallyAdeadlockiswhentwoormoretransactionsaremutuallyholdingandrequestinglocksonthesameresources,creatingacycleofdependenciesDeadlocksoccurwhentransactionstrytolockresourcesinadifferentorderTocombatthisproblem,databasesystemsimplementvariousformsofdeadlockdetectionandtimeoutsLockbehaviorandorderarestorageengine-specific,sosomestorageenginesmightdeadlockonacertainsequenceofstatementseventhoughotherswon’tTransactionTransactionlogginghelpsmaketransactionsmoreInsteadofupdatingthetablesondiskeachtimeachangeoccurs,thestorageenginecanchangeitsinmemorycopyofthedataThestorageenginecanthenwritearecordofthechangetothetransactionlog,whichisondiskandthereforedurableThisisalsoarelativelyfastoperation,becauseappendinglogeventsinvolvessequentialI/OinonesmallareaofthediskinsteadofrandomI/OinmanyplacesThen,atsomelatertime,aprocesscanupdatethetableondiskMySQLABprovidesthreetransactionalstorageengines:MySQLABprovidesthreetransactionalstorageengines:InnoDB,NDBCluster,andFalcon,xtraDBSeveralthird-partyenginesarealsoavailable;thebest-knownenginesrightnowaresolidDBandPBXTMixingstorageenginesinImplicitandexplicitMySQLMySQLoperatesinAUTOCOMMITmodebyYoucanenableordisableAUTOCOMMITforthecurrentconnectionbysettingavariableChangingthevalueofAUTOCOMMIThasnoeffectonnontransactionaltables,suchasMyISAMorMemorytables,whichessentiallyalwaysoperateinAUTOCOMMITmodeIfIfyoumixtransactionalandnontransactionaltables(forinstance,InnoDBandMyISAMtables)inatransaction,thetransactionwillworkproperlyifallgoeswellHowever,ifarollbackisrequired,thechangestothenontransactionaltablecan’tbeundoneMySQLwillnotusuallywarnyouorraiseerrorsifyoudotransactionaloperationsonanontransactionaltableInnoDBusesatwo-phaselockingprotocol.ItcanacquireInnoDBusesatwo-phaselockingprotocol.Itcanacquirelocksatanytimeduringatransaction,butitdoesnotreleasethemuntilaCOMMITorItreleasesallthelocksatthesameThelockingmechanismsdescribedearlierareallInnoDBhandleslocksautomatically,accordingtoyourisolationlevelHowever,However,InnoDBalsosupportsexplicitlocking,whichtheSQLstandarddoesnotmentionatall:SELECT...LOCKINSHARESELECT...FORMySQLalsosupportstheLOCKTABLESandUNLOCKTABLEScommandsImplementedintheserver,notinthestorageThesehavetheiruses,buttheyarenotasubstituteforIfyouneedtransactions,useatransactionalstorageMostMostofMySQL’stransactionalstorageengines,userow-levellockinginconjunctionwithatechniqueforincreasingconcurrencyknownasVItavoidstheneedforlockingatallinmanycasesandcanhavemuchloweroverheadMVCCworksbykeepingasnapshotofthedataasitexistedatsomepointintimeThismeanstransactionscanseeaconsistentviewofthedata,nomatterhowlongtheyrunItalsomeansdifferenttransactionscanseedifferentdatainthesametablesatthesametimeAAisasubsystemthatmanagesMostdatabasemanagementsystemshaveonesubsystemtomanagetables;MySQLServercanusedifferentsubsystems.Becauseastorageengineisappliedatthetablelevel,itissometimescalledeTheMySQLpluggablestorageengineisanarchitecturaldesignthatseparatesthecodethatmanagesthetablesfromthedatabaseservercoreThiscorecodemanagesthecomponentssuchasthequerycache,theoptimizer,andtheconnectionThestorageenginecodehandlestheactualI/OoftheMyISAMMyISAMisthedefaultstorageengineinmysqld,andisthestorageengineusedbythesystemtablesMyISAMprovidesagoodcompromisebetweenperformanceandusefulfeatures,suchasfull-textindexing,compression,andspatial(GIS)functionsMyISAMdoesn’tsupporttransactionsorrow-levelFeatureFeatureNon-NoforeignkeyFULLTEXTindexesfortextNodataIndexcaches—canbespecifiedbyImplementsbothHASHandBTREEindexes(BTREEbyTable-levelVeryfastreadactivity,suitablefordataCompresseddata(withOnlinebackupwithMaximumof64indexesperThreeThreeutilityprogramsaredesignedforworkingwithMyISAMtables:myisamchk—Usedtoanalyze,optimize,andrepairMyISAMtablesmyisampack—Usedtocreatecompressed,read-onlyMyISAMtablesTheThemyisamchkprogramhasfourdifferentmodesofItcanbeusedtoanalyze,optimize,check,andrepairMyISAMtablesThedefaultmodeofoperationisthecheckmodewhereitchecksforpossiblecorruptionTocreatecompressedread-onlyTocreatecompressedread-onlyversionsoftablescanprovideforagoodvperformanceincreasefordatathatisnolongerbeingupdatedbutstillneedstobeAcompressedMyISAMtableisread-only,andcannothavenewrowsinsertedlikeanArchivetablecanOncethecompressionisdoneyouhavetorunthemyisamchkprogramtorebuildindexes--TheMergestorageTheMergestorageengineisactuallyasortofwrappertablethatwrapsaroundMyISAMtableswiththesameschemasAlltheunderlyingtablescanbequeriedatoncebyqueryingtheMergetableMergetableswillusethesamebuffersandconfigurationoptionsasfortheunderlyingMyISAMtablesWhenyoucreateaMergetable,twofilesarealwayscreatedinthefilesystemThereisonefilecontainingthetableformatthathasafilenameofthetablefollowedbyasuffixof.frmThesecondfilealsohasafilenameofthetablebutendswithasuffixof.MRGYoucanalsoputtheindividualMyISAMtablesondifferentharddrivestohelpincreaseperformanceInnoDBwasdesignedfortransactionprocessing—specifically,processingofmanyshort-livedtransactionsInnoDBwasdesignedfortransactionprocessing—specifically,processingofmanyshort-livedtransactionsthatusuallycompleteratherthanbeingrolledbackInnoDBstoresitsdatainaseriesofoneormoredatafilesthatarecollectivelyknownasatablespaceAtablespaceisessentiallyablackboxthatInnoDBmanagesallbyitselfInnoDB’sindexstructuresareverydifferentfromthoseofmostotherMySQLstorageengines.Asaresult,itprovidesveryfastprimarykeylookupsFeatureFeatureTransactionalsupportprovidedbyMVCC(MultiVersionConcurrencyControl)Row-levelForeignkeyIndexingusingclusteredB-treeConfigurablebuffercachingofbothindexesandOnlinenon-blockingbackupthroughseparatecommercialbackupprogramAAtablespaceisalogicalgroupofoneormoredatafilesinadatabaseThefullpathtoeachsharedtablespaceisformedbyaddinginnodb_data_home_dirtoeachpathspecifiedintheinnodb_data_file_pathBydefaultifinnodb_data_file_pathisnotdefined,a10Mbibdata1fileiscreatedinthedatadirectorymysql>SHOWENGINEINNODBByBydefaultInnoDBusesasharedtablespaceforalltablesthatconsistsofoneormorefilesThesefilesareusedtostoremetadataforalltheInnoDBtablesacrossalldatabasesontheserver,andareusuallyreferredtoasibdatafiles,becausethedefaultnameforthefirstfileisibdata1Bydefault,ibdatafilesalsocontainallthedataandindexesforalltheInnoDBtablesWhenanInnoDBtableisdefragmentedinasharedtablespaceconfiguration,theibdatafileswillnotshrink,eventhoughthedataandindexesaresuccessfullyBydefaultibdatafilesarelocatedindatadir.AnyoptionsBydefaultibdatafilesarelocatedindatadir.AnyoptionsfortheInnoDBstorageengineshouldbelistedinthe[mysqld]directiveoftheconfigurationfileTheinnodb_data_home_diroptionisusedtospecifythelocationoftheibdatafilesexplicitly,tostorethemsomewhereotherthandatadirinnodb_data_home_dir=WhenWhendataischanged,affecteddatapagesarechangedintheinnodb_buffer_poolThen,thechangeiswrittentotheredolog,whichinmysqldisstoredintheInnoDBlogfiles(ib_logfile0andib_logfile1)Thepagesaremarkedasdirty,becausetheyhavebeenchanged,andeventuallygetflushedandwrittentodiskSomeofthedifferentparametersfortheInnoDBlogfilesSomeofthedifferentparametersfortheInnoDBlogfilestheirramificationsinnodb_log_files_in_groupissetwithadefaultofThelogfilesarewritteninacircularinnodb_log_file_sizeisthesizeofeachlogfileintheThetotal,combinedsizeofallthelogfileshastobelessthan40,thelogfilesarepurgedwhenmysqldshuts1,whichmeansthatthelogfilesarenotpurgedbeforea2,simulatesacrash,andatthenextstartupInnoDBwilldoainnodb_flush_log_at_trx_commitcontrolshowoftenthefilesarewritten0,tobewrittenandflushedtodiskonceper1,causesthelogbuffertobewrittenandflushedtodiskaftertransaction2,whichcausesthelogbuffertobewrittenaftereverycommitandflushesthelogfilestodiskonceperinnodb_log_buffer_sizeisthewritebufferforInnoDBlogUserUser主講:馬永亮(馬哥QQ群客服QQ:2813150558,TheMySQLaccesscontrolsystemenablesyoutocreateTheMySQLaccesscontrolsystemenablesyoutocreateMySQLaccountsanddefinewhateachaccountcandoAuserinMySQLisacombinationofausernameandhoststringInSQLstatementsthatrequireaccountnames,thenameisgivenin'user_name'@'host_name'formatMySQLMySQLkeepstheACLs(alsocalledgranttables)cachedinmemoryWhenausertriestovauthenticateorrunacommand,MySQLcheckstheauthenticationinformationandpermissionsagainsttheACLs,inapredeterminedorderIfyouarenotsurewhatuseryouareactuallyloggedinasyoucanusetheUSER()andCURRENT_USER()functionstodeterminehowyouareconnectedSHOWGRANTSstatementwithnoargumentsshowstheprivilegesfortheusertheconnectionwasauthenticated—theprivilegesfortheWildcardWildcardcharacters(%and_)areallowedinhostMySQLorderstheaccesscontrollistwiththeleastspecifichostslastHostnamesandIPswithoutwildcardsornetmasksareplacedbeforehostnamesandIPswithwildcardsandAlltheuserandpermissionAlltheuserandpermissioninformationisstoredinthemysqldatabaseinasetoftablesknownasthegranttablesInadditiontothegranttables,themysqldatabasehastablescontainingothersysteminformationForexample,atablecalledeventisusedbytheeventThetablesthatareofinterestwhenitcomes,andtheGRANT,REVOKE,CREATEUSER,DROPUSER,RENAMEUSERcommandsaredesignedforuserToTocreateauser,youcanusetheCREATEUSERTodropauser,youshouldusetheDROPUSERTheRENAMEUSERcommandrenamesanexistingSeveraltypesofprivilegescanbegrantedtoanPrivilegesshouldbegrantedaccordingtohowtheaccountistobeusedWhenWhenyouusestatementssuchasCREATEUSERandGRANT,theserverdeterminesthenecessarymodificationstothegranttablesandmakesthechangesforyouIfyoumodifythetablesdirectlywithastatementsuchasINSERTorDELETE,youmustexplicitlytelltheservertoreloadthetablesafterwardbyusingaFLUSHPRIVILEGESstatementoramysqladminflush-privilegescommandThereTherearealsosomespecialprivilegeALLandALLPRIVILEGESareshorthandfor"allprivilegesexceptGRANTOPTION."USAGEmeans"noprivileges"otherthanbeingallowedtoconnecttotheserverPrivilegescanexistatPrivilegescanexistatdifferentAnyprivilegecanbegrantedglobally.Anaccountpossessesaglobalprivilegecanexerciseitatanytime.GlobalprivilegesarethereforequitepowerfulandarenormallygrantedonlytoadministrativeaccountsSomeprivilegescanbegrantedforspecificdatabases:ALTER,CREATE,CREATETEMPORARYTABLES,CREATEVIEW,DELETE,DROP,GRANTOPTION,INDEX,INSERT,LOCKTABLES,SELECT,SHOWVIEW,andUPDATE.Adatabase-levelprivilegeappliestoalltablesandstoredroutinesintheSomeprivilegescanbegrantedforspecifictables:ALTER,CREATE,DELETE,DROP,GRANTOPTION,INDEX,INSERT,SELECT,andUPDATE.Atable-levelprivilegeappliestoallcolumnsinthetableSomeprivilegescanbegrantedforspecifictablecolumns:INSERT,SELECT,andUPDATESomeprivilegescanbegrantedforspecificstoredroutines:EXECUTE,ALTERROUTINE,andGRANTOPTIONTheuserTheusertablecontainsarecordforeachaccountknowntotheTheuserrecordforanaccountlistsitsglobalItalsoindicatesotherinformationabouttheaccount,suchasanyresourcelimitsitissubjectto,andwhetherclientconnectionsthatusetheaccountmustbemadeoverasecureconnectionusingtheSecureSocketsLayer(SSL)Thedbtablelistsdatabase-specificprivilegesforaccountsThetables_privtableliststable-specificprivilegesforaccountsThecolumns_privtablelistscolumn-specificprivilegesforTheprocs_privtablelistsprivilegesthataccountshaveforstoredproceduresandfunctionsGRNATprivilegesIDENTIFIEDBYGRNATprivilegesIDENTIFIEDBYWhengrantingprivilegesforatableorstoredroutine,thereisanambiguityiftherearemultipleobjects(table,procedure,orfunction)withthesamename.Toindicatethetypeofobjectexplicitly,usethekeywordTABLE,PROCEDURE,orFUNCTIONprecedingthename:ONTABLEONPROCEDUREONFUNCTIONTograntprivilegesatacolumn-specificlevel,useanONclausethatnamesaparticulartable,andspecifyacomma-separatedlistofcolumnnameswithinparenthesesaftereachprivilegetobegrantedGRANTONIfyouwanttogiveanaccountthecapabilitytograntitsprivilegestootheraccounts,addaWITHGRANTOPTIONclausetothestatement.TheThehostpartofanaccountnamemaybegiveninanyofthefollowingformats:ThenameAhostname,suchasAnIPnumber,suchasApatterncontainingthe'%'or'_'wildcardSuchas%.orAhostvalueof%matchesanyhost,allowingtheclienttoconnectfromanywhereAnIPnumber/netmaskThevalueallowsaclienttoconnectfromanyhostwithanaddressthatmatchestheIPnumberforallbitsthatare1inthenetmaskForexample,avalueof/matchesanyhostwith10.0.0inthefirst24bitsofitsIPnumberToTofindoutwhatprivilegesaparticularaccounthas,usetheSHOWGRANTSstatementItdisplaystheGRANTstatementsthatwouldberequiredtosetuptheaccountToseeyourownprivileges,useSHOWGRANTSwithoutanaccountnameorwithCURRENT_USER():SHOWSHOWGRANTSFORToseetheprivilegesforaspecificaccount,specifythataccountnameinthestatementSHOWGRANTFORUsetheREVOKEstatementUsetheREVOKEstatementtorevokeprivilegesfromanaccountREVOKEprivilegesFROMTorevoketheGRANTOPTIONprivilegefromanaccountthathasit,youmustrevokeitinaseparateREVOKEGRANTOPTIONdb.tableUseUsetheSETPASSWORDstatement,specifyingtheaccountnameandthenewpasswordSETPASSWORDFOR‘user’@’host’=Anynon-anonymousclientcanchangeitsownpasswordbyomittingtheFORclause:SETPASSWORD=UseGRANTwiththeUSAGEprivilegespecifieratthegloballevelandanIDENTIFIEDBYclause:GRANTUSAGEON*.*TO‘user'@‘host'BYUSAGEmeans"noprivileges,"sothestatementchangesthepasswordwithoutgrantinganyprivileges.TheThe--skip-grant-tablesoptiontellstheservernottousethegranttablestocontrolclientaccessAnyonecanconnectfromanywherewithnopassword,and,onceconnected,hasfullprivilegestodoanythingThatisconvenientifyou'veforgottentherootpasswordandneedtoresetit,becauseyoucanconnectwithoutknowingthepasswordTopreventremoteclientsfromconnectingoverTCP/IP,youmaywanttousethe--skip-networkingoptionaswell--skip-grant-tablesdisablestheaccount-managementstatements(CREATEUSER,GRANT,REVOKE,SETPASSWORD,andsoforth)TableTableandcolumnprivilegechangesapplytoallstatementsissuedafterthechangesaremadeDatabaseprivilegechangesapplywiththenextUSEChangestoglobalprivilegesandpasswordsdonotapplytoaconnectedclientCachingwithCachingwith主講:馬永亮(馬哥QQ群客服QQ:2813150558,OneOneofthewaysofmakingqueriesrespondfasteristoimplementcachingTheservercanskiptheSQLparsingandoptimizationstagesforrepeatedqueriesTherearethreecommonwaystocachedatawithCreatingmanualcacheUsinginternalcachinginUsingthememcacheddistributedcachingItonlycachesSELECTstatementsandtheircorrespondingItonlycachesSELECTstatementsandtheircorrespondingresultsets,andonlyfordeterministicSELECTstatementsDeterministicSELECTstatementsarestatementsthatalwaysproducethesameresultsnomatterwhat,giventhesameThequerycachestoresarudimentaryhashofthequeryalongwithitsresultsetThequerybeingcomparedmustbebyte-for-byteidenticaltothecachedquery—thequeriesthemselvesarenotcompared;theirhashesarecompared.SothefollowingtwoaredifferentSELECTcustomer_id,namefromSELECTcustomer_id,nameFROMQueriesareviewedasdifferentbythequerycacheiftheyusedifferentdatabases,protocolversions,orcharactersetsFurthermore,notQueriesareviewedasdifferentbythequerycacheiftheyusedifferentdatabases,protocolversions,orcharactersetsFurthermore,notallSELECTstatementswillbecached.SELECTstatementswiththefollowingpropertiesarenotcached:Useofnon-deterministicMostUseofuser-definedUseoftemporarySELECTstatementsinstoredfunctions,triggers,views,andResultsetslargerthanquery_cache_limit(1MbbyUsingQuerycacheinvalidationiswhenaqueryisremovedfromQuerycacheinvalidationiswhenaqueryisremovedfromthequerycachebecauseitsresultsetmayhaveWhenatableismodifiedbyeitherDDLorDML(eitherschemachangesordatachanges),allofthequeriesinthequerycachereferencingthattableareinvalidatedandremoved.QueryQuerycachepruningiswhenaqueryisremovedfromthequerycachebecausethequerycachecannotfindafreeblockinwhichtostoreanewqueryThequerycacheprunesolderentriesusingaleastrecentlyused(LRU)algorithmCachingCachingqueriesisn’tautomaticallymoreefficientthannotcachingIntheory,youcantellwhetherthecacheishelpfulbycomparingtheamountofworktheserverhastodowiththecacheenabledanddisabledIt’shardtoaccuratelycalculateorpredictthequerycache’sThetypeofquerythatbenefitsmostfromcachingisonewhoseresultisexpensivetogeneratebutdoesn’ttakeupmuchspaceinthecachequerycachehitQcache_hits/Com_selectisthestatusvariablethatholdsthenumberofexecutedSELECTqueriesthatgothroughthefullexecutionplanAnyAnySELECTquerythatMySQLdoesn’tservefromthecacheisasAcachemisscanoccurforanyofthefollowingThequeryisnotcacheable,eitherbecauseitcontainsanondeterministicconstruct(suchasCURRENT_DATE)orbecauseitsresultsetistoolargetostoreTheserverhasneverseenthequerybefore,soitneverhadachancetocacheitsresultThequery’sresultwaspreviouslycached,buttheserverremoveditThiscanhappenbecausetherewasn’tenoughmemorytokeepbecausesomeoneinstructedtheservertoremoveorbecauseitwasTheThequerycachefortheserverisstoredcompletelyinmemory,anddoesnotpersistacrossmysqldrestartsAsidefromabout40kofmemoryusedbythequerycache,theentirepoolofmemoryisinitializedasasinglecontiguouschunkofmemoryDuringquerycacheoperationthischunkofmemoryisdividedupintosmallerblocksEachblockmustbeatleastthesizespecifiedbyquery_cache_min_res_unit,whichdefaultsto4KbInadditiontotheseblockscontainingtheresultsetsofthequeriestherearetwohashtablesQueryThelistofdatabasetablesthateachcachedqueryWhenatableismodified,thissecondhashtableisconsultedtodeterminewhichqueriesshouldberemovedduetoquerycacheSevensystemvariablesareusedtocontroltheconfigurationSevensystemvariablesareusedtocontroltheconfigurationandmemoryusageofthequerycacheThevaluesofthesecanbeseenbyusingSHOWGLOBALVARIABLESstatementorintheGLOBAL_VARIABLESsystemviewintheThereThereareeightstatusvariablesrelatingtothequeryThesevariablesareusedformanagingandtuningthequerycacheThevaluesofthesecanbeseenbyusingtheSHOWGLOBALSTATUSstatementorintheGLOBAL_STATUSsystemviewintheWithWithaquerycachetherearetwocausesofTheresultsetsdonotalwaysfitexactlyintoablockofTheinvalidationofqueriesstoredinthecache.WhenaqueryisinvalidateditisdeletedfromthecacheThebestwaytohandlequerycachefragmentationistominimizetheamountoffragmentationTominimizefragmentationistosettheblocksizeofthequerycachetotheaverageresultsetsizeofyour(query_cache_size-TominimizethequerycacheinvalidationandThememcachedcachingsystemisadistributed,in-memorycachesystemthatThememcachedcachingsystemisadistributed,in-memorycachesystemthatspeedsupwebapplicationsbyminimizingtheamountofdatabasequeriesneededThebasicprincipleofmemcachedisthatanumberofmemcacheddaemonsworktogethertoprovidedataisd worktogethertocacheBackupsandBackupsand主講:馬永亮(馬哥QQ群客服QQ:2813150558,BackupsandBackupsand主講:馬永亮(馬哥客服MySQLMySQL主講:馬永亮(馬哥客服bufferbuffer錯錯誤日一般查詢?nèi)章樵內(nèi)斩M制日中繼日事務(wù)日志(redo,查查詢?nèi)誫eneral-general-log-CREATEDATABASECREATEDATABASEUPDATEtbSETINSERINTOtbSET慢慢查詢?nèi)誰og-slow-long-query-slow-query-slow-query-log-錯錯誤日log-log-二二進制日binlog-sql-log-max-binlog- 中中繼日FourFourlogfilesareusedbytheerrorthebinarythegeneralquerytheslowqueryAfifthlogtype,therelaylog,isusedbyaslaveIfthelogsareenabled,mysqldwritesthemtothedatadirectoryunlessotherwisespecifiedBydefault,nologgingisContainsentriesContainsentriesforwhenthemysqlddaemonstartedandstoppedandalsoanycriticalerrorsthatoccurwhiletheserverisrunningInformationsuchaswhentheeventschedulerexecutesaneventandwhenreplicationstartsandstopsisalsowrittentotheerrorlog服務(wù)器啟動和關(guān)閉過程中的信服務(wù)器運行過程中的錯誤信事件調(diào)度器運行一個事件時產(chǎn)生的信在從服務(wù)器上啟動從服務(wù)器進程時產(chǎn)生的信ToenableToenabletheerrorlog,specifythelog-errorTheerrorlogwillbewrittentothedatadirectoryusingtheformathost_name.errTocustomizethefilename,givethelog-erroroptionafilename,suchas:log-Thelog_warningsoptionisusedtocontrolwhetherornotwarningmessagesareloggedtotheerrorlogThedefaultvalueis1Ifthevalueisgreaterthan1,abortedconnectionsarewrittentotheerrorlogIfyoudonotspecifylog-error,orifyouusethe--consoleoptiononWindows,errorsarewrittentostderr,thestandarderroroutputTheThebinarylogsareusedforseveralCanbeusedtoperformapoint-in-timerecoveryduringarecoveryprocess做即時點恢Canbeusedtoenable復Thecontentsofthebinarylogareanystatementsthatoccurintheserverthatcouldpotentiallymodifythedatabases二進制,二進二進制,二進制日志事InsertInsertintostudents(BirthDate)VALUE‘2012-04-08ToToenablebinarylogging,usethelog-binThebinarylogindexfileisaplaintextfilethatkeepstrackofthecurrentbinarylogsBydefault,itsnameismysql-Tosetthefilenameandpathofthebinarylogsandbinarylogindexfile,specifythefollowingoptions:log-bin=log-bin-index=BinaryBinarylogdataisstoredinabinaryTodisplaythebinarylogsintext/readableformatyoumustusethemysqlbin
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 活動板房租賃合同協(xié)議書
- 中介收款合同協(xié)議書范本
- 一種智能出行解決方案
- 共建共用倉庫合同協(xié)議書
- 出租車合伙合同協(xié)議書
- 網(wǎng)絡(luò)營銷年度十大案例
- 夫妻雇傭合同協(xié)議書范本
- 多人股份合同協(xié)議書6
- 中國車用養(yǎng)護品項目創(chuàng)業(yè)計劃書
- 美容美發(fā)行業(yè)數(shù)化店面運營策略
- 2024-2025學年廣東省佛山市南海區(qū)高二下學期素養(yǎng)提升學業(yè)水平測試數(shù)學試卷(含答案)
- 2025年福建福州左海供應(yīng)鏈集團有限公司招聘筆試參考題庫附帶答案詳解
- 2024年濟南產(chǎn)業(yè)發(fā)展投資集團有限公司招聘真題
- 2024年棗莊市滕州市中小學招聘教師筆試真題
- 店面租賃安全協(xié)議書
- 2025年工程財務(wù)分析試題及答案
- 小學校園文化方案
- 財政與金融練習試卷1(共230題)
- 2025年心理健康教育與咨詢考試卷及答案
- 2025年醫(yī)院管理培訓考試試題及答案
- 大學生思想政治教育課件教學
評論
0/150
提交評論