MatchStringCache 正则表达式匹配字符串,并缓存结果
(regex *re.Regexp, s string, cacheLife CacheLife)
| 38 | |
| 39 | // MatchStringCache 正则表达式匹配字符串,并缓存结果 |
| 40 | func MatchStringCache(regex *re.Regexp, s string, cacheLife CacheLife) bool { |
| 41 | if regex == nil { |
| 42 | return false |
| 43 | } |
| 44 | |
| 45 | var regIdString = regex.IdString() |
| 46 | |
| 47 | // 如果长度超过一定数量,大概率是不能重用的 |
| 48 | if cacheLife <= 0 || len(s) > MaxCacheDataSize || !cacheHits.IsGood(regIdString) { |
| 49 | return regex.MatchString(s) |
| 50 | } |
| 51 | |
| 52 | var hash = xxhash.Sum64String(s) |
| 53 | var key = regIdString + "@" + strconv.FormatUint(hash, 10) |
| 54 | var item = SharedCache.Read(key) |
| 55 | if item != nil { |
| 56 | cacheHits.IncreaseHit(regIdString) |
| 57 | return item.Value == 1 |
| 58 | } |
| 59 | var b = regex.MatchString(s) |
| 60 | if b { |
| 61 | SharedCache.Write(key, 1, fasttime.Now().Unix()+cacheLife) |
| 62 | } else { |
| 63 | SharedCache.Write(key, 0, fasttime.Now().Unix()+cacheLife) |
| 64 | } |
| 65 | cacheHits.IncreaseCached(regIdString) |
| 66 | return b |
| 67 | } |
| 68 | |
| 69 | // MatchBytesCache 正则表达式匹配字节slice,并缓存结果 |
| 70 | func MatchBytesCache(regex *re.Regexp, byteSlice []byte, cacheLife CacheLife) bool { |