zhangzengfei
2022-10-18 a13b0a9f5ea78270c4c614865407442748e349be
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package boltcache
 
import "strconv"
 
//添加一条日志
func (ls *LogStore) ApplyLog(logData []byte) {
    lastLogIndex := ls.getLastLog()
    ls.applyCh <- &Log{
        Index: lastLogIndex + 1,
        Data:  logData,
    }
    ls.setLastLog(lastLogIndex + 1)
}
 
type LogCon struct {
    conf *confLog
    Log  *Log
}
 
//获取缓存的数据
func (lc *LogCon) GetData() []byte {
    return lc.Log.Data
}
 
//提供给外层使用,按顺序获取缓存的日志
func (ls *LogStore) Get() *LogCon {
    idx, _ := ls.store.FirstIndex(confBucket)
    cLog := &confLog{}
    if err := ls.store.GetConfLog(idx, cLog); err == nil {
        u, _ := ls.store.FirstIndex(cLog.BucketName)
        log := &Log{}
        if err = ls.store.GetLog(cLog.BucketName, u, log); err == nil {
            log.Index = u
            cLog.Index = int(idx)
            return &LogCon{
                conf: cLog,
                Log:  log,
            }
        } else {
            if size, _ := ls.store.Size(confBucket); size > 1 {
                ls.Delete(&LogCon{
                    conf: cLog,
                    Log:  nil,
                })
            }
            ls.printLog("Get log err:", err)
        }
    } else {
        ls.printLog("Get conf idx:", idx, "err:", err)
    }
    return nil
}
 
// 遍历数据, 输出原始数据
func (ls *LogStore) ForEach(f func(v *LogCon) error) error {
    return ls.store.ForEach(f)
}
 
func (ls *LogStore) Size() int {
    start, _ := ls.store.FirstIndex(confBucket)
    end, _ := ls.store.LastIndex(confBucket)
 
    totalSize := 0
 
    for ; start <= end; start++ {
        bucketName := bucketPre + strconv.Itoa(int(start))
        bucketSize, err := ls.store.Size(bucketName)
        if err == nil {
            totalSize = totalSize + bucketSize
        }
    }
 
    return totalSize
}
 
//提供给外层使用,删除日志
func (ls *LogStore) Delete(lc *LogCon) error {
    return ls.store.Delete(lc)
}
 
func (ls *LogStore) Close() error {
    return ls.store.Close()
}