@@ -69,39 +69,21 @@ func NewPersistentCache(
69
69
persistentDuration time.Duration ,
70
70
handleError func (error ),
71
71
) (* Cache , error ) {
72
- err := os .MkdirAll (filepath .Dir (persistentFilePath ), 0700 )
73
- if err != nil {
74
- return nil , err
75
- }
76
- unlockFunc , err := lockCachePersistentFile (persistentFilePath , false , handleError )
77
- if err != nil {
78
- return nil , err
79
- }
80
- defer unlockFunc ()
81
-
82
- file , closeFunc , err := openCachePersistentFile (persistentFilePath , handleError )
83
- if err != nil {
84
- return nil , err
85
- }
86
- defer closeFunc ()
87
-
88
- cacheMap , err := loadCacheMapFrom (valueType , file )
89
- if err != nil {
90
- return nil , err
91
- }
92
-
93
- return & Cache {
72
+ c := & Cache {
94
73
persistentFile : & persistentFile {
95
74
valueType : valueType ,
96
75
cacheFilePath : persistentFilePath ,
97
76
persistentDuration : persistentDuration ,
98
77
lastPersistentTime : time .Now (),
99
78
handleError : handleError ,
100
79
},
101
- cacheMap : cacheMap ,
80
+ cacheMap : nil ,
102
81
compactInterval : compactInterval ,
103
82
lastCompactTime : time .Now (),
104
- }, nil
83
+ }
84
+ // 为了兼容上层接口,此处允许加载本地缓存文件失败
85
+ _ = c .loadLocalCache ()
86
+ return c , nil
105
87
}
106
88
107
89
type GetResult uint8
@@ -114,6 +96,39 @@ const (
114
96
NoResultGot GetResult = 4
115
97
)
116
98
99
+ func (cache * Cache ) loadLocalCache () error {
100
+ defer func () {
101
+ if cache .cacheMap == nil {
102
+ cache .cacheMap = make (map [string ]cacheValue )
103
+ }
104
+ }()
105
+
106
+ persistentFilePath := cache .persistentFile .cacheFilePath
107
+ err := os .MkdirAll (filepath .Dir (persistentFilePath ), 0700 )
108
+ if err != nil {
109
+ return err
110
+ }
111
+ unlockFunc , err := lockCachePersistentFile (persistentFilePath , false , cache .persistentFile .handleError )
112
+ if err != nil {
113
+ return err
114
+ }
115
+ defer unlockFunc ()
116
+
117
+ file , closeFunc , err := openCachePersistentFile (persistentFilePath , cache .persistentFile .handleError )
118
+ if err != nil {
119
+ return err
120
+ }
121
+ defer closeFunc ()
122
+
123
+ cacheMap , err := loadCacheMapFrom (cache .persistentFile .valueType , file )
124
+ if err != nil {
125
+ return err
126
+ }
127
+
128
+ cache .cacheMap = cacheMap
129
+ return nil
130
+ }
131
+
117
132
func (cache * Cache ) Get (key string , fallback func () (CacheValue , error )) (CacheValue , GetResult ) {
118
133
cache .cacheMapMutex .Lock ()
119
134
value , ok := cache .cacheMap [key ]
0 commit comments