SoFunction
Updated on 2025-03-04

Detailed explanation of the example of GoFrame framework cache query results

I will continue to work hard in the following articles and will introduce you to the knowledge points related to GoFrame framework caching, as well as some summary and thoughts in the use of my own project. GoFrame framework is referred to as gf.

Today I will introduce you to you:How to elegantly cache query results in GoFrame

Query cache

gdbIt supports cache processing of query results, which is often used in query cache scenarios with more read and less write, and supports manual cache cleaning.

It should be noted that query cache only supports chain operations and is not available under transaction operations.

Related methods:

func (m *Model) Cache(duration , name ... string) *Model
  • Important reminder: Transaction queries do not support caching.
  • When duration < 0 means clearing the cache, when duration=0 means expired, when duration > 0 means expired, time unit of duration expired: seconds;
  • Name represents a custom cache name, which facilitates the business layer to accurately locate cache items (if the business layer needs to manually clean it, the cache name must be specified)

Cache Objects

ORMObjects provide cache management objects by default, and the cache object type is*, that is, it also supports*All features of .

Can be passedGetCache() *The interface method obtains the cache object and implements various customized cache operations through the returned object, such as:().GetCache().Keys()

Cache Adaptation (Redis Cache)

By defaultORMof*The cache object provides a single-process memory cache. Although the performance is very efficient, it can only be used within a single process.

If the service is deployed by multiple nodes, the cache between multiple nodes may cause data inconsistency, so in most scenarios we useRedisThe server implements the cache of database query data.

*The object adopts the adapter design pattern, which can easily switch from single-process memory cache to distributedRediscache.

The sample code is as follows, isn't it very elegant:

adapter := (())
().GetCache().SetAdapter(adapter)

RedisThe cache is based on querySQLAs the key name, the query result is used as the key value.

passCacheThe chain method is very convenient to write and clear caches.

Example of usage

Data table structure

CREATE TABLE `user` (
  `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL DEFAULT '' COMMENT 'Nick name',
  `site` varchar(255) NOT NULL DEFAULT '' COMMENT 'website',
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Sample code

package main
import (
    "/gogf/gf/database/gdb"
    "/gogf/gf/frame/g"
    "time"
)
func main() {
    db := ()
    // Turn on debug mode to facilitate recording of all executed SQL    (true)

    // Execute 2 queries and cache the query results for 1 hour, and execute cache name (optional)    for i := 0; i &lt; 2; i++ {
        r, _ := ("user").Cache(, "test-user").Where("uid", 1).One()
        ().Print(())
    }
    // Perform update operations and clean the query cache with the specified name    _, err := ("user").Cache(-1, "test-user").Data({"name": "One Piece"}).Where("uid", 1).Update()
    if err != nil {
        ().Fatal(err)
    }
    // Execute the query again and enable the query cache feature    r, _ := ("user").Cache(, "test-user").Where("uid", 1).One()
    ().Print(())
}

The output result after execution is (the test table data structure is for example reference only):

2022-06-15 21:44:12.228 [DEBU] [1 ms] SELECT * FROM `user` WHERE uid=1 LIMIT 1
2022-06-15 21:44:12.228 {"name":"Wang Zhongyang","site":"/user/2189882892232029","uid":1}
2022-06-15 21:44:12.228 {"name":"Wang Zhongyang","site":"/user/2189882892232029","uid":1}
2022-06-15 21:44:12.299 [DEBU] [1 ms] UPDATE `user` SET `name`='One Piece' WHERE uid=1
2022-06-15 21:44:12.300 [DEBU] [1 ms] SELECT * FROM `user` WHERE uid=1 LIMIT 1
2022-06-15 21:44:12.300 {"name":"One Piece","site":"/user/2189882892232029","uid":1}

Tips

To facilitate the display of cache effects, data is enabled heredebugFeature: When there is any SQL operation, it will be output to the terminal.

Analysis of operation results

  • Execute twiceOneMethod data query, the first time I went to SQL query, the second time I used the cache directly, and SQL was not submitted to the database for execution.Therefore, only one query SQL is printed here, and the results of the two queries are also the same.
  • Note that a custom name is set for the cache of this query.test-user, so as to clear the update cache later. If the cache does not need to be cleaned, you can do not need to set the cache name.
  • When executedUpdateDuring the update operation, the specified cache is also cleared according to the name.
  • Then executeOneMethod data query, and then the new data is cached again.

Summarize

GoFrame'sgdbIsn't the cache processing of query results very elegant? Especially*The object adopts the adapter design pattern, which can easily switch from single-process memory cache to distributedRediscache.

This is the end of this article about how GoFrame is elegantly cached query results. For more related contents of GoFrame cached query results, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!