63 lines
1.7 KiB
Go
63 lines
1.7 KiB
Go
package controller
|
|
|
|
import (
|
|
"dypid/db"
|
|
"dypid/global"
|
|
"dypid/model"
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func ReadDataHandler(c *gin.Context) {
|
|
lLen := global.RDB.LLen(global.RCtx, fmt.Sprintf("list:%s", c.Query("token")))
|
|
if lLen.Val() == 0 {
|
|
c.JSON(200, gin.H{"result": "数据库没有数据"})
|
|
return
|
|
}
|
|
retData := global.RDB.BLPop(global.RCtx, 0, fmt.Sprintf("list:%s", c.Query("token")))
|
|
newData := model.Data{}
|
|
err := json.Unmarshal([]byte(retData.Val()[1]), &newData)
|
|
if err != nil {
|
|
c.JSON(400, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(200, gin.H{"result": newData})
|
|
}
|
|
func WriteDataHandler(c *gin.Context) {
|
|
data := model.Data{}
|
|
|
|
if err := c.BindQuery(&data); err != nil {
|
|
c.JSON(400, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
dedupObject, err := db.GetDedupObject(data.Token)
|
|
if err != nil {
|
|
c.JSON(400, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
err = createBF(fmt.Sprintf("dedup:%s:%s", data.Token, dedupObject), 0.01, 100000000)
|
|
if err != nil && err.Error() != "ERR item exists" {
|
|
c.JSON(400, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
exists := global.RDB.BFExists(global.RCtx, fmt.Sprintf("dedup:%s:%s", data.Token, dedupObject), c.Query(dedupObject))
|
|
if exists.Val() {
|
|
return
|
|
}
|
|
marshal, err := json.Marshal(data)
|
|
if err != nil {
|
|
return
|
|
}
|
|
global.RDB.LPush(global.RCtx, fmt.Sprintf("list:%s", data.Token), marshal)
|
|
global.RDB.BFAdd(global.RCtx, fmt.Sprintf("dedup:%s:%s", data.Token, dedupObject), c.Query(dedupObject))
|
|
c.JSON(200, gin.H{"result": "ok"})
|
|
}
|
|
|
|
func createBF(bloomFilter string, errorRate float64, capacity int64) error {
|
|
_, err := global.RDB.BFReserve(global.RCtx, bloomFilter, errorRate, capacity).Result()
|
|
return err
|
|
}
|