Skip to content

Commit

Permalink
优化entries的查询,新增部分查询功能
Browse files Browse the repository at this point in the history
  • Loading branch information
侯锐 committed Aug 21, 2019
1 parent 381e6bd commit 624869f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 9 deletions.
6 changes: 3 additions & 3 deletions common/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,15 @@ func AppendEntryList(entryList []Entry) {
}

// 根据key获取entry
func GetEntryByKey(key string) string {
func GetEntryByKey(key string) (string, bool) {
defer entryMutex.Unlock()
entryMutex.Lock()
for i := len(logEntries) - 1; i >= 0; i-- {
if logEntries[i].Key == key {
return logEntries[i].Value
return logEntries[i].Value, true
}
}
return ""
return "", false
}

// 根据索引获取Entry
Expand Down
48 changes: 42 additions & 6 deletions http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"log"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
Expand Down Expand Up @@ -93,11 +94,12 @@ func StartHttpServer(port uint) {
key := r.URL.Query().Get("key")
if key == "" {
entries := common.GetEntries()
_, err := fmt.Fprintf(w, "Total entries: %d\n", len(entries))
from, size := getFromAndSize(r.URL.Query().Get("from"), r.URL.Query().Get("size"), len(entries))
_, err := fmt.Fprintf(w, "Total entries: %d, from: %d, size: %d\n", len(entries), from, size)
if err != nil {
log.Fatal(err)
}
for _, entry := range entries {
for _, entry := range entries[from : from+size] {
_, err := fmt.Fprintf(w, `{"key": "%s", "value": "%s", "index": "%d", "term": "%d", "time": "%s"}`+"\n",
entry.Key, entry.Value, entry.Index, entry.Term,
time.Unix(int64(entry.Time), 0).Format("2006-01-02 15:04:05"))
Expand All @@ -107,10 +109,18 @@ func StartHttpServer(port uint) {
}
return
}
value := common.GetEntryByKey(key)
_, err := fmt.Fprintf(w, `{"%s": "%s"}`, key, value)
if err != nil {
log.Fatal(err)
value, ok := common.GetEntryByKey(key)
if ok {
_, err := fmt.Fprintf(w, `{"%s": "%s"}`, key, value)
if err != nil {
log.Fatal(err)
}
} else {
w.WriteHeader(http.StatusNotFound) // 没找到相应的key
_, err := fmt.Fprintf(w, "can't found key [%s]", key)
if err != nil {
log.Fatal(err)
}
}
case http.MethodPost:
if common.LeaderNodeId == "" {
Expand Down Expand Up @@ -264,3 +274,29 @@ func postJson(url string, data []byte) (int, http.Header, []byte) {
}
return res.StatusCode, res.Header, body
}

// 解析得到合适的from和size属性的值
func getFromAndSize(fromStr, sizeStr string, entriesLength int) (from, size int) {
var err error
from, err = strconv.Atoi(fromStr)
if err != nil {
from = 0
}
size, err = strconv.Atoi(sizeStr)
if err != nil {
size = 10
}

if from >= entriesLength || from < 0 {
from = 0
}

if size > entriesLength || size < 0 {
size = 10
}

if from+size > entriesLength {
size = entriesLength - from
}
return
}

0 comments on commit 624869f

Please sign in to comment.