gf/os/gfile/gfile_z_example_cache_test.go

44 lines
1.1 KiB
Go
Raw Normal View History

2021-11-17 14:14:19 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2021-11-05 14:30:50 +08:00
package gfile_test
import (
"fmt"
"time"
"github.com/gogf/gf/v2/os/gfile"
)
func ExampleGetContentsWithCache() {
// init
2021-11-11 13:01:32 +08:00
var (
fileName = "gflie_example.txt"
tempDir = gfile.Temp("gfile_example_cache")
2021-11-11 13:01:32 +08:00
tempFile = gfile.Join(tempDir, fileName)
)
2021-11-05 14:30:50 +08:00
// write contents
2021-11-11 13:01:32 +08:00
gfile.PutContents(tempFile, "goframe example content")
2021-11-05 14:30:50 +08:00
2021-11-17 19:50:03 +08:00
// It reads the file content with cache duration of one minute,
// which means it reads from cache after then without any IO operations within on minute.
2021-11-11 13:01:32 +08:00
fmt.Println(gfile.GetContentsWithCache(tempFile, time.Minute))
2021-11-05 14:30:50 +08:00
// write new contents will clear its cache
2021-11-11 13:01:32 +08:00
gfile.PutContents(tempFile, "new goframe example content")
2021-11-05 14:30:50 +08:00
2021-11-17 19:50:03 +08:00
// There's some delay for cache clearing after file content change.
time.Sleep(time.Second * 1)
2021-11-05 14:30:50 +08:00
// read contents
2021-11-11 13:01:32 +08:00
fmt.Println(gfile.GetContentsWithCache(tempFile))
2021-11-05 14:30:50 +08:00
2021-11-13 23:42:03 +08:00
// May Output:
2021-11-11 13:01:32 +08:00
// goframe example content
// new goframe example content
2021-11-05 14:30:50 +08:00
}