教程專用隨堂mysql03_第1頁
教程專用隨堂mysql03_第2頁
教程專用隨堂mysql03_第3頁
教程專用隨堂mysql03_第4頁
教程專用隨堂mysql03_第5頁
已閱讀5頁,還剩180頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

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錯錯誤日一般查詢日慢查詢日二進制日中繼日事務日志(redo,查查詢日general-general-log-CREATEDATABASECREATEDATABASEUPDATEtbSETINSERINTOtbSET慢慢查詢日log-slow-long-query-slow-query-slow-query-log-錯錯誤日log-log-二二進制日binlog-sql-log-max-binlog- 中中繼日FourFourlogfilesareusedbytheerrorthebinarythegeneralquerytheslowqueryAfifthlogtype,therelaylog,isusedbyaslaveIfthelogsareenabled,mysqldwritesthemtothedatadirectoryunlessotherwisespecifiedBydefault,nologgingisContainsentriesContainsentriesforwhenthemysqlddaemonstartedandstoppedandalsoanycriticalerrorsthatoccurwhiletheserverisrunningInformationsuchaswhentheeventschedulerexecutesaneventandwhenreplicationstartsandstopsisalsowrittentotheerrorlog服務器啟動和關閉過程中的信服務器運行過程中的錯誤信事件調度器運行一個事件時產生的信在從服務器上啟動從服務器進程時產生的信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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論