-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.go
More file actions
57 lines (48 loc) · 1.74 KB
/
Copy pathexample.go
File metadata and controls
57 lines (48 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Command example demonstrates wtcache: writes go straight through to the
// remote fs while staying cached in memory for a short TTL, so reads within
// the TTL never touch the remote fs.
package main
import (
"fmt"
"log"
"time"
cache "github.com/kdihalas/write-through-cache"
"github.com/spf13/afero"
)
func main() {
// Stand-in for a real remote fs (e.g. S3, SFTP, NFS-backed afero.Fs).
remote := afero.NewOsFs()
remoteDir := "/tmp/wtcache-example"
if err := remote.MkdirAll(remoteDir, 0o755); err != nil {
log.Fatalf("mkdir remote dir: %v", err)
}
// Synchronous write-through: Write/Close only return once the remote
// write has completed, so the demo below is deterministic. Pass
// cache.WithAsync(onError) to New instead for write-behind semantics.
fs := cache.New(remote, 2*time.Second)
defer fs.Close()
path := remoteDir + "/hello.txt"
if err := afero.WriteFile(fs, path, []byte("hello from cache"), 0o644); err != nil {
log.Fatalf("write: %v", err)
}
// Read immediately: served from the in-memory cache.
data, err := afero.ReadFile(fs, path)
if err != nil {
log.Fatalf("read (cached): %v", err)
}
fmt.Printf("cached read: %s\n", data)
// Mutate the remote file directly, bypassing the cache, to prove the
// next read within the TTL still comes from memory.
if err := afero.WriteFile(remote, path, []byte("changed on remote"), 0o644); err != nil {
log.Fatalf("out-of-band remote write: %v", err)
}
data, _ = afero.ReadFile(fs, path)
fmt.Printf("still cached: %s\n", data)
// Wait out the TTL, then read again: falls through to remote.
time.Sleep(3 * time.Second)
data, err = afero.ReadFile(fs, path)
if err != nil {
log.Fatalf("read (expired): %v", err)
}
fmt.Printf("after TTL expiry, read-through: %s\n", data)
}