”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 解锁 MySQL 性能:掌握查询缓存优化

解锁 MySQL 性能:掌握查询缓存优化

发布于2024-08-23
浏览:847

Unlock MySQL Performance: Mastering Query Cache Optimization

What is the Query Cache?

The Query Cache is a feature in MySQL designed to boost database performance by caching the results of SELECT queries. When a query that's been executed before is run again, MySQL can quickly pull the result from this cache instead of re-executing it against the database. This not only speeds up data retrieval but also reduces the load on the database, making it highly efficient for frequently run queries with consistent parameters.

How the Query Cache Works

Whenever a query is issued, MySQL first looks in the Query Cache to check if the result of an identical query has been stored previously. If there’s a match, MySQL bypasses the usual query execution process and directly serves the cached result. This is much faster as it avoids the time-consuming steps of query processing and disk access, leveraging the speed of memory access instead.

We now turn to the critical query cache variables – query_cache_type, query_cache_size, query_cache_limit, and query_cache_min_res_unit – and their impact on MySQL performance.

1. query_cache_type

The query_cache_type variable in MySQL controls whether the query cache is enabled, disabled, or set to operate only on demand.

query_cache_type Usage

The query cache stores the text of a SELECT statement together with the corresponding result that was sent to the client. If an identical statement is received later, the server retrieves the results from the cache rather than parsing and executing the statement again. Enabling the query cache can significantly reduce the time it takes to get results for frequently run queries by serving them from memory rather than re-executing them.

Setting the query_cache_type variable in MySQL to different values determines how the query cache behaves:

  • 0 (OFF) – Disables the query cache, although a buffer of query_cache_size bytes is still allocated.

  • 1 (ON) – Enables the query cache for all SELECT queries unless SQL_NO_CACHE is specified in the query.

  • 2 (DEMAND) – Enables the query cache only for queries that explicitly use the SQL CACHE clause.

query_cache_type Configuration

Query_cache_type can be configured offline or online, when the server is running. Configuration may be preferred online, to allow for testing. When the server is restarted the query_cache_type will revert.

Command Line Configuration:
mysqld> set global query_cache_type = XX

Replace XX with a value to suit your database needs. To verify that the variable has been changed:

mysqld> show global variables like 'query_cache_type'

Configuration File:
[mysqld]
query_cache_type
= XX

Replace XX with a value to suit your database needs. Restart MySQL server.

query_cache_type Considerations

According to general recommendations, you should set query_cache_type to 1 (ON) for environments where the data changes infrequently but reads are frequent. Set to 0 (OFF) in highly dynamic environments where the overhead of maintaining the cache may outweigh the benefits.

Enabling the query cache indiscriminately may not always yield performance benefits and can even degrade performance in some scenarios. Consider the following factors when configuring query_cache_type:

  • The size of the query cache – A larger cache can hold more query results but requires more memory.

  • Query patterns – Queries with frequently changing results or large result sets may not benefit from caching.

  • Cache invalidation – Updates, inserts, or deletes on cached tables invalidate corresponding cache entries, leading to cache churn.

  • Concurrency – The query cache is not suitable for highly concurrent workloads due to contention issues.

  • MySQL version – The query cache feature has been deprecated in MySQL 5.7 and removed in MySQL 8.0, as it has limitations and can cause contention in multi-threaded environments.

2. query_cache_size

Specifies the amount of memory allocated to store the results of cached queries. It's a primary factor in determining how many results can be cached at once.

query_cache_size Usage

The query_cache_size variable determines the amount of memory allocated for the query cache. This value should be adjusted based on the nature of your workload and available memory resources:

  • Small Result Sets – If your application frequently executes queries that return small result sets, a larger query cache size can be beneficial. This allows more queries to be stored in the cache, reducing the need for query execution.

  • Frequent Identical Queries – In scenarios where the same queries are executed repeatedly, increasing the query_cache_size can improve performance by caching these queries and their results.

  • Query Cache Hit Ratio – Monitoring the query cache hit ratio can provide insights into the effectiveness of the cache. If the hit ratio is low, increasing the query_cache_size may help improve cache efficiency.

query_cache_size Configuration

Query_cache_size can be configured offline or online, when the server is running. Configuration may be preferred online, to allow for testing. When the server is restarted the query_cache_size will revert.

Command Line Configuration:
mysqld> set global query_cache_size = XX

Replace XX with a value to suit your database needs. To verify that the variable has been changed:

mysqld> show global variables like 'query_cache_size'

Configuration File:
_[mysqld]
query_cache_size _= XX

Replace XX with a value to suit your database needs. Restart MySQL server.

query_cache_size Considerations

The query_cache_size should be set based on the available memory and the nature of your workload. Setting it too large can lead to memory exhaustion, while setting it too small may limit its effectiveness.

Monitoring the utilization of the cache (hits versus inserts) will guide appropriate sizing. Start with a moderate size, like 64MB to 128MB, and adjust based on the performance and available system memory.

Consider the following factors when configuring query_cache_size:

  • Query patterns – Queries with frequently changing results or large result sets may not benefit from caching.

  • Cache invalidation – Updates, inserts, or deletes on cached tables invalidate corresponding cache entries, leading to cache churn.

  • Concurrency – The query cache is not suitable for highly concurrent workloads due to contention issues.

  • MySQL version – The query cache feature has been deprecated in MySQL 5.7 and removed in MySQL 8.0 due to limitations and contention in multi-threaded environments..

3. query_cache_limit

This variable sets the maximum size for individual query results that can be cached. It prevents large queries from consuming a disproportionate amount of the cache space.

query_cache_limit Usage

When a query result exceeds the query_cache_limit, the result is not cached. This prevents excessively large or resource-intensive queries from filling up the cache with results that might not be reused frequently. By setting an appropriate value for query_cache_limit, you can ensure that only smaller, more commonly used query results are cached, optimizing the use of memory.

query_cache_limit Configuration

Query_cache_limit can be configured offline or online, when the server is running. Configuration may be preferred online, to allow for testing. When the server is restarted the query_cache_limit will revert.

Command Line Configuration:
mysqld> set global query_cache_limit = XX

Replace XX with a value to suit your database needs. To verify that the variable has been changed:

mysqld> show global variables like 'query_cache_limit'

Configuration File:
[mysqld]
query_cache_limit
= XX

Replace XX with a value to suit your database needs. Restart MySQL server.

query_cache_limit Considerations

It is typically recommended to set query_cache_limit between 1MB and 4MB, depending on the nature of the queries and the available cache size. It's important to note that setting query_cache_limit too low may result in useful query results being excluded from the cache, reducing the effectiveness of the query cache.

4. query_cache_min_res_unit

The query_cache_min_res_unit variable in MySQL determines the minimum size in bytes for blocks allocated by the query cache. This setting impacts the efficiency of the query cache by controlling the granularity of cached results.

query_cache_min_res_unit Usage

When a query result is stored in the query cache, it occupies a certain amount of memory. The query_cache_min_res_unit variable defines the minimum size of memory blocks allocated for these cached results. If a query result is smaller than this value, it will still occupy the minimum size defined by query_cache_min_res_unit.

query_cache_min_res_unit Configuration

Query_cache_min_res_unit can be configured offline or online, when the server is running. Configuration may be preferred online, to allow for testing. When the server is restarted the query_cache_min_res_unit will revert.

Command Line Configuration:
mysqld> set global query_cache_min_res_unit = XX

Replace XX with a value to suit your database needs. To verify that the variable has been changed:

mysqld> show global variables like 'query_cache_min_res_unit'
_
Configuration File:
_[mysqld]
query_cache_min_res_unit
= XX

Replace XX with a value to suit your database needs. Restart MySQL server.

query_cache_min_res_unit Considerations

Configuring query_cache_min_res_unit involves setting the variable to a suitable value that balances memory consumption with caching efficiency. The value should be chosen based on the average size of query results in your workload.

  • A smaller value may lead to more efficient memory usage but could increase overhead due to more cache entries.

  • Conversely, a larger value may reduce the number of cache entries but could lead to wasted memory for smaller query results.

Analyze your workload to determine the average size of query results. Adjust the value of query_cache_min_res_unit based on this analysis to achieve a balance between memory consumption and caching efficiency. For most setups, this will fall between 16MB and 64MB.

Enable and Tune the Query Cache in 4 Steps

The query cache was deprecated as of MySQL 5.7.20 and fully removed in MySQL 8.0. If your version of MySQL is still able to use query_cache, it has to be enabled because it is disabled by default. To enable and configure the query cache in MySQL, MariaDB, or Percona, you will typically need to access your server’s my.cnf or my.ini file. Here’s a step-by-step approach:

1. Enable Query Cache – Set query_cache_type to 1 or 2. Setting query_cache_type or query_cache_size to zero will always disable the cache. For selective caching (recommended for most use cases), you would use:

query_cache_type = 1

  1. Set Cache Size – Define query_cache_size. A starting point might be 10-20% of your total available memory, but this requires tuning based on your workload:

query_cache_size = 100M

3. Define Result Size Limit – Configure query_cache_limit to control the size of results stored. This might start at a few megabytes, depending on your typical query size:

query_cache_limit = 2M

4. Adjust Minimum Result Unit – Modify query_cache_min_res_unit based on your needs. Reducing this below the default can help utilize cache space more efficiently, especially if you expect a lot of small queries:

query_cache_min_res_unit = 512

Monitoring Query Cache with Health Checks

QCache Fragmentation is a key indicator of the Query Cache's performance in MySQL. This feature is built to store the results of SELECT queries so that repeated requests can be fulfilled quickly without needing to rerun the query, thereby boosting performance. However, as time passes, the Query Cache can become fragmented, leading to reduced effectiveness.

Calculate QCache Fragmentation

Check out our comprehensive Health Checks documentation, which contains information and step-by-step instructions on how to calculate QCache Fragmentation.

Once you have calculated the QCache Fragmentation and QcacheDeleteRate, you need to interpret the results. Ideally, the QCache Fragmentation should be less than 10, and the QcacheDeleteRate should be less than 20.

Recommended Actions

If the QCache Fragmentation is high, you may need to adjust the size of the Query Cache to reduce fragmentation. If the QcacheDeleteRate is high, you may need to increase the size of the Query Cache or optimize your queries to reduce the number of INSERTs.

Optimize Your Query Cache with Ease

Tuning the MySQL Query Cache involves adjusting several settings to optimize database performance, from managing memory usage to reducing query times. While the variables discussed here form a good foundation, effective management requires continuous monitoring and updates based on actual system load and performance.

To simplify this process, consider using a powerful management tool like Releem that automates these adjustments. Such a tool can continuously monitor your system's performance and dynamically update the query_cache settings in real-time.

This allows you time to focus on broader goals while Releem handles the intricacies of Query Cache optimization.

版本声明 本文转载于:https://dev.to/drupaladmin/unlock-mysql-performance-mastering-query-cache-optimization-4fg4?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何防止游戏网站页面加载时重复插入?
    如何防止游戏网站页面加载时重复插入?
    调试页面加载时的重复插入在游戏网页上,观察到用户活动查询在页面刷新时将重复记录插入数据库。$insert_user_activity = mysql_query("INSERT INTO game_activity (user_id,user_full_name,game_id,game_...
    编程 发布于2024-11-06
  • Python 最佳实践:编写干净、高效且可维护的代码
    Python 最佳实践:编写干净、高效且可维护的代码
    Python 因其简单性、可读性和多功能性而成为最流行的编程语言之一。 无论您是经验丰富的开发人员还是初学者,遵循 Python 最佳实践对于编写干净、高效和可维护的代码至关重要。 在这篇博文中,我们将探讨编写 Python 代码时要牢记的一些关键最佳实践。 1 - 遵守 PEP...
    编程 发布于2024-11-06
  • std::lock_guard 与 std::scoped_lock:何时使用哪个锁?
    std::lock_guard 与 std::scoped_lock:何时使用哪个锁?
    std::lock_guard 与 std::scoped_lock:为任务选择正确的锁随着 C 17 的引入,std ::scoped_lock 类与现有的 std::lock_guard 一起出现,引发了关于它们之间的差异以及何时使用它们的问题。虽然 std::scoped_lock 与 std...
    编程 发布于2024-11-06
  • WebRTC简介
    WebRTC简介
    安装和代码指南 WebRTC(网络实时通信)是一种开源技术,可通过网络浏览器和移动应用程序中的简单 API 实现实时通信。它允许在点之间直接共享音频、视频和数据,无需中间服务器,非常适合视频会议、直播和文件共享等应用。 在本博客中,我们将深入探讨以下主题: 什么是WebRTC? W...
    编程 发布于2024-11-06
  • 如何在不使用 JavaScript 的情况下使用 CSS 隐藏和显示内容?
    如何在不使用 JavaScript 的情况下使用 CSS 隐藏和显示内容?
    使用 CSS 隐藏和显示内容:无需 JavaScript 的技巧在进行 Web 开发时,控制内容的可见性通常至关重要。传统上,这是使用 JavaScript 实现的,但 CSS 也可用于创建优雅的隐藏和显示效果。下面描述了一种此类技术,解决了先前方法遇到的特定挑战。隐藏/显示内容切换:可以使用 CS...
    编程 发布于2024-11-06
  • 如何创建重复最少的 5 个字符的随机字符串?
    如何创建重复最少的 5 个字符的随机字符串?
    生成 5 个具有最少重复的随机字符要创建具有最少重复的随机 5 个字符字符串,最有效的方法之一是使用PHP 函数和巧妙技术的结合。让我们深入研究解决方案:使用 md5 和 rand$rand = substr(md5(microtime()),rand(0,26),5);该方法使用md5哈希函数根据...
    编程 发布于2024-11-06
  • 如何在 Go 中处理不同包之间相同的方法签名?
    如何在 Go 中处理不同包之间相同的方法签名?
    处理不同包中具有相同方法签名的接口在Go中,当处理具有相同方法签名但定义在不同包中的多个接口时,可能会出现以下情况实现两个接口的类型会导致意外行为。考虑在不同包中定义的这两个接口(Doer)和函数(FuncA 和 FuncB):// Package A type Doer interface { D...
    编程 发布于2024-11-06
  • 如何使用 jQuery 填充级联下拉列表以获得更好的兼容性和用户体验?
    如何使用 jQuery 填充级联下拉列表以获得更好的兼容性和用户体验?
    使用 jQuery 填充级联下拉列表在表单开发领域,级联下拉列表经常用于提供更加用户友好和动态体验。为了增强兼容性并解决跨浏览器问题,jQuery 提供了一个强大的解决方案来异步填充这些下拉列表。问题中所示的用于创建级联下拉列表的原始 JavaScript 函数缺乏与 IE 的兼容性。为了解决这个问...
    编程 发布于2024-11-06
  • 了解 JavaScript 中的扩展运算符:初学者简单指南
    了解 JavaScript 中的扩展运算符:初学者简单指南
    介绍 JavaScript 是一种有趣的编程语言,其最令人兴奋的功能之一是扩展运算符。如果您刚刚开始编码,或者即使您是一个对学习 JavaScript 感兴趣的孩子,也不必担心!我将以最简单的方式分解这个概念,并举例来帮助您理解。 什么是价差运算符? 扩展运算符看起...
    编程 发布于2024-11-06
  • 在 Python 中使用 OpenSearch 掌握 CRUD 操作:实用指南
    在 Python 中使用 OpenSearch 掌握 CRUD 操作:实用指南
    OpenSearch, an open-source alternative to Elasticsearch, is a powerful search and analytics engine built to handle large datasets with ease. In this b...
    编程 发布于2024-11-06
  • 冰沙框架的重要概念||如何精通冰沙
    冰沙框架的重要概念||如何精通冰沙
    要精通 Frappe,有几个关键概念和领域需要关注。以下是最重要的细分: 1. 文档类型 定义:DocTypes是Frappe中的核心数据模型。每个实体或记录都存储在 DocType 中,并且它们可以具有字段、权限和工作流程。 为什么它很重要:了解如何创建和自定义 DocType 至...
    编程 发布于2024-11-06
  • 如何解决 JLabel 拖放的鼠标事件冲突?
    如何解决 JLabel 拖放的鼠标事件冲突?
    用于拖放的 JLabel 鼠标事件:解决鼠标事件冲突为了在 JLabel 上启用拖放功能,鼠标事件必须被覆盖。然而,当尝试使用 mousePressed 事件实现拖放时,会出现一个常见问题,因为 mouseReleased 事件对该 JLabel 无效。提供的代码在 mousePressed 事件中...
    编程 发布于2024-11-06
  • MySQL 中的数据库分片:综合指南
    MySQL 中的数据库分片:综合指南
    随着数据库变得越来越大、越来越复杂,有效地控制性能和扩展就出现了。数据库分片是用于克服这些障碍的一种方法。称为“分片”的数据库分区将大型数据库划分为更小、更易于管理的段(称为“分片”)。通过将每个分片分布在多个服务器上(每个服务器保存总数据的一小部分),可以提高可扩展性和吞吐量。 在本文中,我们将探...
    编程 发布于2024-11-06
  • 如何将 Python 日期时间对象转换为秒?
    如何将 Python 日期时间对象转换为秒?
    在 Python 中将日期时间对象转换为秒在 Python 中使用日期时间对象时,通常需要将它们转换为秒以适应各种情况分析目的。但是,toordinal() 方法可能无法提供所需的输出,因为它仅区分具有不同日期的日期。要准确地将日期时间对象转换为秒,特别是对于 1970 年 1 月 1 日的特定日期...
    编程 发布于2024-11-06
  • 如何使用 Laravel Eloquent 的 firstOrNew() 方法有效优化 CRUD 操作?
    如何使用 Laravel Eloquent 的 firstOrNew() 方法有效优化 CRUD 操作?
    使用 Laravel Eloquent 优化 CRUD 操作在 Laravel 中使用数据库时,插入或更新记录是很常见的。为了实现这一点,开发人员经常求助于条件语句,在决定执行插入或更新之前检查记录是否存在。firstOrNew() 方法幸运的是, Eloquent 通过firstOrNew() 方...
    编程 发布于2024-11-06

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3