백엔드 개발 PHP 튜토리얼 一个有关MYSQL的文章.E文的.MySQLs Query Cache_PHP教程

一个有关MYSQL的文章.E文的.MySQLs Query Cache_PHP教程

Jul 13, 2016 pm 05:27 PM
cache http mysql query 기사 ~의


http://www.discuz.net/viewthread.php?tid=43137&sid=G4jizDNovember 18, 2003MySQLs Query CacheBy Ian GilfillanA typical scenarioBoss: Our new website is crawling! How can it be, we have four state-of-the-art web servers - whats the problem?You: Well, the web servers are fine - its the database server thats struggling.Boss: What? You told me this MySQL thing was fast, that we didnt need Oracle, and now you say it cant cope! How can this be?You: Well, the web servers are behaving so well that theyre pushing through lots of queries, and the database cant manage to process all of them at the same time. Its only one database, and lots of web servers...Boss: Its too late to buy Oracle now - what are we going to do!?Big Boss to Boss(in the bosss mind): This project has been a disaster from the beginning - now you want me to delay it while we install a new database, and spend a whole lot more! Do you think were made of money!? Im calling in someone who knows what theyre doing - youre history buddy.Colleague (about to take your job): Wait, I think I can solve the problem!So, what does your colleague know that you dont? How can he save the day and let the boss get all the credit? Our scenario is too imprecise to generalize, and there are many possible solutions. You can read about optimizing queries and indexes, optimizing by improving the hardware, and tweaking the MySQL variables, using the slow query log, and of course, there are other methods such as replication. However, MySQL 4 provides one feature that can prove very handy - a query cache. In a situation where the database has to repeatedly run the same queries on the same data set, returning the same results each time, MySQL can cache the result set, avoiding the overhead of running through the data over and over. Usually, you would want to implement some sort of caching on the web server, but there are times when this is not possible, and then it is the query cache you will look to for help.Setting up the query cacheTo make sure MySQL uses the query cache, there are a few variables you need to set in the configuration file (usually my.cnf or my.ini). First, is the query_cache_type. There are three possible settings: 0 (for off, do not use), 1 (for on, cache queries) and 2 (on demand, discussed more below). To ensure it is always on, place: query-cache-type = 1in the configuration file. If you started the server having only made this change, you would see the following cache variables set: mysql> SHOW VARIABLES LIKE %query_cache%;+-------------------+---------+| Variable_name | Value |+-------------------+---------+| have_query_cache | YES || query_cache_limit | 1048576 || query_cache_size | 0 || query_cache_type | ON |+-------------------+---------+4 rows in set (0.06 sec)Note that these are results from MySQL 4.0.x - youll see more in versions 4.1.x and beyond. The query_cache_type will be set to ON or OFF as appropriate. However, there is one more to set, and that is the query_cache_size. If set to 0 (the default), the cache will be disabled. This variable determines the memory, in bytes, used for the query cache. For our purposes, we will set it to 20 MB: query-cache-size = 20MThe amount is shown in bytes: mysql> SHOW VARIABLES LIKE %query_cache%;+-------------------+----------+| Variable_name | Value |+-------------------+----------+| have_query_cache | YES || query_cache_limit | 1048576 || query_cache_size | 20971520 || query_cache_type | ON |+-------------------+----------+4 rows in set (0.06 sec)The Query cache in action (almost)For this tutorial, I used a dump from Wikipedia, the open content encyclopedia (you can find the dumps here. I am using a fairly slow machine, with nothing else happening on it, to minimize interference in the results. Lets run the same query twice, and see how much improvement we see the second time: SELECT * FROM cur;...14144 rows in set (2.96 sec)Now we run the same query again: SELECT * FROM cur; 14144 rows in set (3.02 sec) Now we run the same query again: SELECT * FROM cur; 14144 rows in set (3.02 sec) What is happening? We would expect the second query to take noticeably less time. Lets examine some of the status variables to get a better picture. mysql> SHOW STATUS LIKE %qcache%;+-------------------------+----------+| Variable_name | Value |+-------------------------+----------+| Qcache_queries_in_cache | 0 || Qcache_inserts | 2 || Qcache_hits | 0 || Qcache_lowmem_prunes | 0 || Qcache_not_cached | 2 || Qcache_free_memory | 20962720 || Qcache_free_blocks | 1 || Qcache_total_blocks | 1 |+-------------------------+----------+8 rows in set (0.00 sec)The two queries we ran are both recorded (by Qcache_inserts), but neither of them have been cached. (You may get different results if other queries have been running.) The problem is that the result set is too big. I used the Wikipedia Esperanto dump (4MB compressed - the English dump is 135MB, and even though my English is better than my Esperanto, bandwidth is expensive in South Africa!), but it is immaterial, as even that is more than the query cache can handle by default. There are two limits in play here - the limit for each individual query is determined by the value of query_cache_limit, which is 1MB by default. Moreover, the limit of the cache in total is determined by query_cache_size, which we have seen already. The former limit applies here. If a result set is greater than 1M, it is not cached. The Query cache in action (really)Lets try a smaller query: SELECT cur_is_new FROM cur WHERE cur_user_text > Y...2336 rows in set (0.38 sec)Lets see if this one was cached:mysql> SHOW STATUS LIKE %qcache%;+-------------------------+----------+| Variable_name | Value |+-------------------------+----------+| Qcache_queries_in_cache | 1 || Qcache_inserts | 3 || Qcache_hits | 0 || Qcache_lowmem_prunes | 0 || Qcache_not_cached | 2 || Qcache_free_memory | 20947592 || Qcache_free_blocks | 1 || Qcache_total_blocks | 4 |+-------------------------+----------+8 rows in set (0.00 sec)There is now a query in the cache. If it took 0.38 seconds to run the first time, lets see if we notice an improvement the second time: SELECT cur_is_new FROM cur WHERE cur_user_text > Y...2336 rows in set (0.11 sec)Much better! And, looking at the status again: mysql> SHOW STATUS LIKE %qcache%;+-------------------------+----------+| Variable_name | Value |+-------------------------+----------+| Qcache_queries_in_cache | 1 || Qcache_inserts | 3 || Qcache_hits | 1 || Qcache_lowmem_prunes | 0 || Qcache_not_cached | 2 || Qcache_free_memory | 20947592 || Qcache_free_blocks | 1 || Qcache_total_blocks | 4 |+-------------------------+----------+8 rows in set (0.06 sec)The cache has been hit once. The status variables above should be fairly self-explanatory. Available memory for the cache has gone from 20962720 to 20947592 bytes. The most useful variable for future tuning is Qcache_lowmem_prunes. Each time a cached query is removed from the query cache, (because MySQL needs to make space for another), this value will be incremented. If it increases quickly, and you still have memory to spare, you can up the query_cache_size, while if it never increases, you can reduce the cache size. Lets run the query again, with a slight difference, as follows: SELECT cur_is_new from cur where cur_user_text > Y...2336 rows in set (0.33 sec)That took longer than we would have expected. Lets look at the status variables to see whats up: mysql> SHOW STATUS LIKE %qcache%;+-------------------------+----------+| Variable_name | Value |+-------------------------+----------+| Qcache_queries_in_cache | 2 || Qcache_inserts | 4 || Qcache_hits | 1 || Qcache_lowmem_prunes | 0 || Qcache_not_cached | 2 || Qcache_free_memory | 20932976 || Qcache_free_blocks | 1 || Qcache_total_blocks | 6 |+-------------------------+----------+The query has not made use of the cache - in fact, MySQL has inserted another query in the cache! The proble

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/531868.htmlTechArticlehttp://www.discuz.net/viewthread.php?tid=43137+-------------------+---------+| Variable_name | Value |+-------------------+---------+| have_query_cache | YES || query_cache_limit |...
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

MySQL 사용자와 데이터베이스의 관계 MySQL 사용자와 데이터베이스의 관계 Apr 08, 2025 pm 07:15 PM

MySQL 데이터베이스에서 사용자와 데이터베이스 간의 관계는 권한과 테이블로 정의됩니다. 사용자는 데이터베이스에 액세스 할 수있는 사용자 이름과 비밀번호가 있습니다. 권한은 보조금 명령을 통해 부여되며 테이블은 Create Table 명령에 의해 생성됩니다. 사용자와 데이터베이스 간의 관계를 설정하려면 데이터베이스를 작성하고 사용자를 생성 한 다음 권한을 부여해야합니다.

Redshift Zero ETL과의 RDS MySQL 통합 Redshift Zero ETL과의 RDS MySQL 통합 Apr 08, 2025 pm 07:06 PM

데이터 통합 ​​단순화 : AmazonRdsMysQL 및 Redshift의 Zero ETL 통합 효율적인 데이터 통합은 데이터 중심 구성의 핵심입니다. 전통적인 ETL (추출, 변환,로드) 프로세스는 특히 데이터베이스 (예 : AmazonRDSMySQL)를 데이터웨어 하우스 (예 : Redshift)와 통합 할 때 복잡하고 시간이 많이 걸립니다. 그러나 AWS는 이러한 상황을 완전히 변경 한 Zero ETL 통합 솔루션을 제공하여 RDSMYSQL에서 Redshift로 데이터 마이그레이션을위한 단순화 된 거의 실시간 솔루션을 제공합니다. 이 기사는 RDSMYSQL ZERL ETL 통합으로 Redshift와 함께 작동하여 데이터 엔지니어 및 개발자에게 제공하는 장점과 장점을 설명합니다.

MySQL은 지불해야합니다 MySQL은 지불해야합니다 Apr 08, 2025 pm 05:36 PM

MySQL에는 무료 커뮤니티 버전과 유료 엔터프라이즈 버전이 있습니다. 커뮤니티 버전은 무료로 사용 및 수정할 수 있지만 지원은 제한되어 있으며 안정성이 낮은 응용 프로그램에 적합하며 기술 기능이 강합니다. Enterprise Edition은 안정적이고 신뢰할 수있는 고성능 데이터베이스가 필요하고 지원 비용을 기꺼이 지불하는 응용 프로그램에 대한 포괄적 인 상업적 지원을 제공합니다. 버전을 선택할 때 고려 된 요소에는 응용 프로그램 중요도, 예산 책정 및 기술 기술이 포함됩니다. 완벽한 옵션은없고 가장 적합한 옵션 만 있으므로 특정 상황에 따라 신중하게 선택해야합니다.

고로드 애플리케이션의 MySQL 성능을 최적화하는 방법은 무엇입니까? 고로드 애플리케이션의 MySQL 성능을 최적화하는 방법은 무엇입니까? Apr 08, 2025 pm 06:03 PM

MySQL 데이터베이스 성능 최적화 안내서 리소스 집약적 응용 프로그램에서 MySQL 데이터베이스는 중요한 역할을 수행하며 대규모 트랜잭션 관리를 담당합니다. 그러나 응용 프로그램 규모가 확장됨에 따라 데이터베이스 성능 병목 현상은 종종 제약이됩니다. 이 기사는 일련의 효과적인 MySQL 성능 최적화 전략을 탐색하여 응용 프로그램이 고 부하에서 효율적이고 반응이 유지되도록합니다. 실제 사례를 결합하여 인덱싱, 쿼리 최적화, 데이터베이스 설계 및 캐싱과 같은 심층적 인 주요 기술을 설명합니다. 1. 데이터베이스 아키텍처 설계 및 최적화 된 데이터베이스 아키텍처는 MySQL 성능 최적화의 초석입니다. 몇 가지 핵심 원칙은 다음과 같습니다. 올바른 데이터 유형을 선택하고 요구 사항을 충족하는 가장 작은 데이터 유형을 선택하면 저장 공간을 절약 할 수있을뿐만 아니라 데이터 처리 속도를 향상시킬 수 있습니다.

MySQL의 쿼리 최적화는 데이터베이스 성능을 향상시키는 데 필수적입니다. 특히 대규모 데이터 세트를 처리 할 때 MySQL의 쿼리 최적화는 데이터베이스 성능을 향상시키는 데 필수적입니다. 특히 대규모 데이터 세트를 처리 할 때 Apr 08, 2025 pm 07:12 PM

1. 올바른 색인을 사용하여 스캔 한 데이터의 양을 줄임으로써 데이터 검색 속도를 높이십시오. 테이블 열을 여러 번 찾으면 해당 열에 대한 인덱스를 만듭니다. 귀하 또는 귀하의 앱이 기준에 따라 여러 열에서 데이터가 필요한 경우 복합 인덱스 2를 만듭니다. 2. 선택을 피하십시오 * 필요한 열만 선택하면 모든 원치 않는 열을 선택하면 더 많은 서버 메모리를 선택하면 서버가 높은 부하 또는 주파수 시간으로 서버가 속도가 느려지며, 예를 들어 Creation_at 및 Updated_at 및 Timestamps와 같은 열이 포함되어 있지 않기 때문에 쿼리가 필요하지 않기 때문에 테이블은 선택을 피할 수 없습니다.

MySQL 사용자 이름 및 비밀번호를 작성하는 방법 MySQL 사용자 이름 및 비밀번호를 작성하는 방법 Apr 08, 2025 pm 07:09 PM

MySQL 사용자 이름 및 비밀번호를 작성하려면 : 1. 사용자 이름과 비밀번호를 결정합니다. 2. 데이터베이스에 연결; 3. 사용자 이름과 비밀번호를 사용하여 쿼리 및 명령을 실행하십시오.

MySQL을 복사하여 붙여 넣는 방법 MySQL을 복사하여 붙여 넣는 방법 Apr 08, 2025 pm 07:18 PM

MySQL에서 복사 및 붙여 넣기 단계는 다음 단계가 포함됩니다. 데이터를 선택하고 CTRL C (Windows) 또는 CMD C (MAC)로 복사; 대상 위치를 마우스 오른쪽 버튼으로 클릭하고 페이스트를 선택하거나 Ctrl V (Windows) 또는 CMD V (Mac)를 사용하십시오. 복사 된 데이터는 대상 위치에 삽입되거나 기존 데이터를 교체합니다 (데이터가 이미 대상 위치에 존재하는지 여부에 따라).

MySQL을 보는 방법 MySQL을 보는 방법 Apr 08, 2025 pm 07:21 PM

다음 명령으로 MySQL 데이터베이스를보십시오. 서버에 연결하십시오. mysql -u username -p password run show database; 기존의 모든 데이터베이스를 가져 오려는 명령 데이터베이스 선택 : 데이터베이스 이름 사용; 보기 테이블 : 테이블 표시; 테이블 구조보기 : 테이블 이름을 설명합니다. 데이터보기 : 테이블 이름에서 *를 선택하십시오.

See all articles