README
¶
bks
s:=map[string]interface{}{}
_, err = config.EsClient.Index().
Index("").
BodyJson(s).
Do(context.Background())
boolQuery := elastic.NewBoolQuery()
match := elastic.NewMatchQuery("name", req.Name)
boolQuery.Must(match)
rangeQuery := elastic.NewRangeQuery("price").Gte(req.MinPrice).Lte(req.MaxPrice)
boolQuery.Must(rangeQuery)
rangeQuery := elastic.NewRangeQuery("expiration").Gte(req.MinTime).Lte(req.MaxTime)
boolQuery.Must(rangeQuery)
sort := elastic.NewFieldSort("_score").Desc()
if req.Stort != "" {
split := strings.Split(req.Stort, "_")
if len(split) == 2 && split[0] == "price" {
sort = elastic.NewFieldSort("price")
if split[1] == "desc" {
sort.Desc()
} else {
sort.Asc()
}
}
}
highlight:=elastic.NewHighlight()
highlight = highlight.Field().
PreTags("<span style=\"color:red;\">").
PostTags("</span>")
res, err := config.EsClient.Search("").
Query().
Size().
From().
SortBy().
Highlight().
Do(context.Background())
var list []*
for _, hit := range res.Hits.Hits {
p := new()
err := json.Unmarshal(hit.Source, p)
if err != nil {
return nil, errors.New("瑙f瀽澶辫触")
}
h,ok:=hit.Highlight[]
if ok{
p.Name = strings.join(h," ")
}
list = append(list, p)
}
// ES 淇敼 鈥?鍏?Get 鏌ュ嚭瀹屾暣鏂囨。锛屾敼鐩爣瀛楁锛屽啀 Index 瑕嗙洊鍐欏洖
// 涓嶈鐢?Update+Doc 鐩存帴鏀癸紝瀹规槗瑕嗙洊鎺夊叾浠栧瓧娈?id := strconv.Itoa(int(req.Id))
// 1. 鏌ュ嚭鐜版湁鏂囨。
getResult, err := config.EsClient.Get().
Index("note_index").
Id(id).
Do(context.Background())
if err != nil {
return nil, err
}
// 2. 鍙嶅簭鍒楀寲鍒扮粨鏋勪綋
var note model.Note
json.Unmarshal(getResult.Source, ¬e)
// 3. 鍙敼浣犺鏀圭殑瀛楁锛屽叾浠栧瓧娈典笉鍙?note.Title = req.Title // 淇敼鏍囬
note.Content = req.Content // 淇敼鍐呭
// 4. 搴忓垪鍖栧悗鏁存潯瑕嗙洊鍐欏洖锛堝悓 ID 鍗虫洿鏂帮級
s, _ := json.Marshal(note)
_, err = config.EsClient.Index().
Index("note_index").
Id(id).
BodyJson(string(s)).
Do(context.Background())
if err != nil {
return nil, err
}
// ES 鍒犻櫎 鈥?鎸?ID 鍒犻櫎鏂囨。
id := strconv.Itoa(int(req.Id))
_, err := config.EsClient.Delete().
Index("note_index").
Id(id).
Do(context.Background())
if err != nil {
return nil, err
}
// Redis 鍒濆鍖?rdb := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
})
_, err := rdb.Ping(context.Background()).Result()
// Redis Set / Get
rdb.Set(context.Background(), "key", "value", time.Hour)
val, err := rdb.Get(context.Background(), "key").Result()
if err == redis.Nil {
// key 涓嶅瓨鍦?}
// Redis 缂撳瓨 JSON 瀵硅薄
b, _ := json.Marshal(obj)
rdb.Set(context.Background(), fmt.Sprintf("cache:%s", key), b, 30*time.Minute)
var cached Obj
json.Unmarshal([]byte(rdb.Get(context.Background(), key).Val()), &cached)
// Redis 鍒楄〃鍒嗛〉
rdb.LPush(context.Background(), "listKey", item1, item2)
list, err := rdb.LRange(context.Background(), "listKey", 0, 9).Result() // 绗?椤?0鏉?count, _ := rdb.LLen(context.Background(), "listKey").Result()
// Redis 楠岃瘉鐮侀檺娴?key := fmt.Sprintf("sms:%s", mobile)
count, _ := rdb.Incr(context.Background(), key).Result()
if count == 1 {
rdb.Expire(context.Background(), key, time.Minute)
}
if count > 3 {
return errors.New("鍙戦€佽繃浜庨绻?)
}
// Redis 鍒嗗竷寮忛攣
key := fmt.Sprintf("lock:%d", id)
ok, _ := rdb.SetNX(context.Background(), key, "1", 10*time.Second).Result()
if !ok {
return errors.New("鎿嶄綔杩涜涓?)
}
defer rdb.Del(context.Background(), key)
// Redis ZSet 鎺ㄦ媺娴?鈥?绗旇鍙戝竷鎺ㄩ€佸埌绮変笣Feed
const FeedMaxSize = 1000 // 绮変笣Feed鏈€澶ф暟閲?
func notePushToFansFeed(id int64, fans []model.Fans) {
pipe := rdb.GetClient().Pipeline()
ctx := context.Background()
for _, v := range fans {
key := fmt.Sprintf("feed:follow:%d", v.FollowerId)
pipe.ZAdd(ctx, key, redis.Z{
Score: float64(time.Now().Unix()),
Member: fmt.Sprintf("%d", id),
})
pipe.ZRemRangeByRank(ctx, key, 0, int64(-FeedMaxSize-1))
}
_, err := pipe.Exec(ctx)
if err != nil {
fmt.Println("鍙戦€佸埌绮変笣feed澶辫触", err)
return
}
}
// Redis ZSet 澶姹?鈥?绮変笣瓒呴槇鍊艰蛋澶姹犳媺妯″紡
const BigVLatestKey = "big:v:latest"
const BigVPoolMaxSize = 10000
func addToBigVPool(id int64) {
pipe := rdb.GetClient().Pipeline()
ctx := context.Background()
pipe.ZAdd(ctx, BigVLatestKey, redis.Z{
Score: float64(time.Now().Unix()),
Member: fmt.Sprintf("%d", id),
})
pipe.ZRemRangeByRank(ctx, BigVLatestKey, 0, int64(-BigVPoolMaxSize-1))
_, _ = pipe.Exec(ctx)
}
// 鍙戝竷绗旇鏃跺垽鏂帹杩樻槸鎷?fans, _ := repository.NewNoteRepository(db).GetFans(userId)
if len(fans) < 1000 {
notePushToFansFeed(noteId, fans) // 鏅€氱敤鎴?鈫?鎺ㄥ埌绮変笣Feed
} else {
addToBigVPool(noteId) // 澶 鈫?鍐欏叆澶姹狅紝绮変笣鎷夊彇
}
// 绮変笣鎷夊彇Feed
key := fmt.Sprintf("feed:follow:%d", userId)
feedIds, _ := rdb.ZRevRange(context.Background(), key, 0, 19).Result() // 鏈€鏂?0鏉?```
```go
nowDay := time.Now().Truncate(24 * time.Hour)
if parse.Before(nowDay) {
return nil, errors.New("")
}
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
err = tx.Commit().Error
if err != nil {
return nil, errors.New("浜嬪姟鎻愪氦澶辫触")
}
License
MIT License
Click to show internal directories.
Click to hide internal directories.