8000 docs: formatting the code in the readme by BaiZe1998 · Pull Request #5 · hertz-contrib/cache · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

docs: formatting the code in the readme #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ import (

"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/hertz-contrib/cache"
"github.com/hertz-contrib/cache/persist"
"github.com/hertz-contrib/cache"
"github.com/hertz-contrib/cache/persist"
)

func main() {
Expand Down Expand Up @@ -87,12 +87,12 @@ import (
"context"
"net/http"
"time"

"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/go-redis/redis/v8"
"github.com/hertz-contrib/cache"
"github.com/hertz-contrib/cache/persist"
"github.com/hertz-contrib/cache"
"github.com/hertz-contrib/cache/persist"
)

func main() {
Expand Down
8 changes: 4 additions & 4 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ import (

"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/hertz-contrib/cache"
"github.com/hertz-contrib/cache/persist"
"github.com/hertz-contrib/cache"
"github.com/hertz-contrib/cache/persist"
)

func main() {
Expand Down Expand Up @@ -90,8 +90,8 @@ import (
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/go-redis/redis/v8"
"github.com/hertz-contrib/cache"
"github.com/hertz-contrib/cache/persist"
"github.com/hertz-contrib/cache"
"github.com/hertz-contrib/cache/persist"
)

func main() {
Expand Down
9 changes: 7 additions & 2 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,10 @@ type GetCacheStrategyByRequest func(ctx context.Context, c *app.RequestContext)
const (
errMissingCacheStrategy = "[CACHE] cache strategy is nil"
getCacheErrorFormat = "[CACHE] get cache error: %s, cache key: %s"
setCacheKeyErrorFormat = "[CACHE] set cache key error"
setCacheKeyErrorFormat = "[CACHE] set cache key error: %s, cache key: %s"
getRequestUriIgnoreQueryOrderErrorFormat = "[CACHE] getRequestUriIgnoreQueryOrder error: %s"
writeResponseErrorFormat = "[CACHE] write response error: %s"
singleFlightErrorFormat = "[CACHE] call the function in-flight error: %s"
)

// NewCache user must pass getCacheKey to describe the way to generate cache key
Expand Down Expand Up @@ -151,7 +152,7 @@ func newCache(
}

inFlight := false
rawRespCache, _, _ := sfGroup.Do(cacheKey, func() (interface{}, error) {
rawRespCache, err, _ := sfGroup.Do(cacheKey, func() (interface{}, error) {
if options.singleFlightForgetTimeout > 0 {
forgetTimer := time.AfterFunc(options.singleFlightForgetTimeout, func() {
sfGroup.Forget(cacheKey)
Expand All @@ -176,6 +177,10 @@ func newCache(
return respCache, nil
})

if err != nil {
hlog.CtxErrorf(ctx, singleFlightErrorFormat, err)
}

if !inFlight {
replyWithCache(ctx, c, options, rawRespCache.(*ResponseCache))
options.shareSingleFlightCallback(ctx, c)
Expand Down
4 changes: 2 additions & 2 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,8 @@ func WithSingleFlightForgetTimeout(forgetTimeout time.Duration) Option {
}
}

// IgnoreQueryOrder will ignore the queries order in url when generate cache key . This option only takes effect in CacheByRequestURI function
func IgnoreQueryOrder(b bool) Option {
// WithIgnoreQueryOrder will ignore the queries order in url when generate cache key . This option only takes effect in CacheByRequestURI function
func WithIgnoreQueryOrder(b bool) Option {
return Option{
F: func(o *Options) {
o.ignoreQueryOrder = b
Expand Down
129 changes: 129 additions & 0 deletions options_test.go
8000
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* Copyright 2022 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2021 cyhone
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* This file may have been modified by CloudWeGo authors. All CloudWeGo
* Modifications are Copyright 2022 CloudWeGo Authors.
*/

package cache

import (
"context"
"testing"
"time"

"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/common/test/assert"
)

func TestOptions(t *testing.T) {
options := Options{
getCacheStrategyByRequest: func(ctx context.Context, c *app.RequestContext) (bool, Strategy) {
return true, Strategy{
CacheKey: "test-key1",
}
},
hitCacheCallback: defaultHitCacheCallback,
missCacheCallback: defaultMissCacheCallback,
beforeReplyWithCacheCallback: defaultBeforeReplyWithCacheCallback,
shareSingleFlightCallback: defaultShareSingleFlightCallback,
singleFlightForgetTimeout: 1 * time.Second,
ignoreQueryOrder: false,
prefixKey: "prefix1",
withoutHeader: false,
}

w, x, y, z := "", "", "", ""

f, strategy := options.getCacheStrategyByRequest(nil, nil)
assert.DeepEqual(t, "test-key1", strategy.CacheKey)
assert.True(t, f)
options.hitCacheCallback(nil, nil)
assert.DeepEqual(t, "", w)
options.missCacheCallback(nil, nil)
assert.DeepEqual(t, "", x)
options.beforeReplyWithCacheCallback(nil, nil)
assert.DeepEqual(t, "", y)
options.shareSingleFlightCallback(nil, nil)
assert.DeepEqual(t, "", z)
assert.DeepEqual(t, 1*time.Second, options.singleFlightForgetTimeout)
assert.DeepEqual(t, "prefix1", options.prefixKey)
assert.False(t, options.ignoreQueryOrder)
assert.False(t, options.withoutHeader)

opts := make([]Option, 0)
opts = append(opts,
WithCacheStrategyByRequest(func(ctx context.Context, c *app.RequestContext) (bool, Strategy) {
return true, Strategy{
CacheKey: "test-key2",
}
}),
WithOnHitCache(func(c context.Context, ctx *app.RequestContext) {
w = "W"
}),
WithOnMissCache(func(c context.Context, ctx *app.RequestContext) {
x = "X"
}),
WithBeforeReplyWithCache(func(c *app.RequestContext, cache *ResponseCache) {
y = "Y"
}),
WithSingleFlightForgetTimeout(2*time.Second),
WithOnShareSingleFlight(func(ctx context.Context, c *app.RequestContext) {
z = "Z"
}),
WithIgnoreQueryOrder(true),
WithoutHeader(true),
WithPrefixKey("prefix2"),
)

options.Apply(opts)

f, strategy = options.getCacheStrategyByRequest(nil, nil)
assert.DeepEqual(t, "test-key2", strategy.CacheKey)
assert.True(t, f)
options.hitCacheCallback(nil, nil)
assert.DeepEqual(t, "W", w)
options.missCacheCallback(nil, nil)
assert.DeepEqual(t, "X", x)
options.beforeReplyWithCacheCallback(nil, nil)
assert.DeepEqual(t, "Y", y)
options.shareSingleFlightCallback(nil, nil)
assert.DeepEqual(t, "Z", z)
assert.DeepEqual(t, 2*time.Second, options.singleFlightForgetTimeout)
assert.DeepEqual(t, "prefix2", options.prefixKey)
assert.True(t, options.ignoreQueryOrder)
assert.True(t, options.withoutHeader)
}
9 changes: 8 additions & 1 deletion persist/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,14 @@ import (
"reflect"
"time"

"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/jellydator/ttlcache/v2"
)

const (
setTTLErrorFormat = "[CACHE] set ttl for memory store error: %s"
)

// MemoryStore local memory cache store
type MemoryStore struct {
Cache *ttlcache.Cache
Expand All @@ -57,7 +62,9 @@ type MemoryStore struct {
// NewMemoryStore allocate a local memory store with default expiration
func NewMemoryStore(defaultExpiration time.Duration) *MemoryStore {
cacheStore := ttlcache.NewCache()
_ = cacheStore.SetTTL(defaultExpiration)
if err := cacheStore.SetTTL(defaultExpiration); err != nil {
hlog.Errorf(setTTLErrorFormat, err)
}

// disable SkipTTLExtensionOnHit default
cacheStore.SkipTTLExtensionOnHit(true)
Expand Down
0