example updates for package gcache

This commit is contained in:
John
2021-08-27 01:01:41 +08:00
parent 5b57c35522
commit b316b9c073
4 changed files with 79 additions and 3 deletions

View File

@ -0,0 +1,28 @@
package main
import (
"fmt"
"github.com/gogf/gf/os/gcache"
"github.com/gogf/gf/os/gctx"
"time"
)
func main() {
var (
ch = make(chan struct{}, 0)
ctx = gctx.New()
key = `key`
value = `value`
)
for i := 0; i < 10; i++ {
go func(index int) {
<-ch
_, _ = gcache.Ctx(ctx).GetOrSetFuncLock(key, func() (interface{}, error) {
fmt.Println(index, "entered")
return value, nil
}, 0)
}(i)
}
close(ch)
time.Sleep(time.Second)
}

View File

@ -0,0 +1,19 @@
package main
import (
"fmt"
"github.com/gogf/gf/os/gcache"
"github.com/gogf/gf/os/gctx"
)
func main() {
var (
ctx = gctx.New()
key1 int32 = 1
key2 float64 = 1
value = `value`
)
_ = gcache.Ctx(ctx).Set(key1, value, 0)
fmt.Println(gcache.Ctx(ctx).Get(key1))
fmt.Println(gcache.Ctx(ctx).Get(key2))
}

View File

@ -0,0 +1,29 @@
package main
import (
"fmt"
"github.com/gogf/gf/os/gcache"
"github.com/gogf/gf/os/gctx"
)
func main() {
type User struct {
Id int
Name string
Site string
}
var (
ctx = gctx.New()
user *User
key = `UserKey`
value = &User{
Id: 1,
Name: "GoFrame",
Site: "https://goframe.org",
}
)
_ = gcache.Ctx(ctx).Set(key, value, 0)
v, _ := gcache.Ctx(ctx).GetVar(key)
_ = v.Scan(&user)
fmt.Printf(`%#v`, user)
}

View File

@ -27,10 +27,10 @@ func (c *Cache) Sets(data map[interface{}]interface{}, duration time.Duration) e
}
// SetIfNotExist sets cache with `key`-`value` pair which is expired after `duration`
// if `key` does not exist in the cache. It returns true the `key` dose not exist in the
// if `key` does not exist in the cache. It returns true the `key` does not exist in the
// cache, and it sets `value` successfully to the cache, or else it returns false.
//
// The parameter `value` can be type of <func() interface{}>, but it dose nothing if its
// The parameter `value` can be type of <func() interface{}>, but it does nothing if its
// result is nil.
//
// It does not expire if `duration` == 0.
@ -122,7 +122,7 @@ func (c *Cache) Size() (size int, err error) {
}
// Data returns a copy of all key-value pairs in the cache as map type.
// Note that this function may leads lots of memory usage, you can implement this function
// Note that this function may lead lots of memory usage, you can implement this function
// if necessary.
func (c *Cache) Data() (map[interface{}]interface{}, error) {
return c.adapter.Data(c.getCtx())