GoFrame 緩存管理-Redis緩存

2022-04-01 10:22 更新

基本介紹

緩存組件同時(shí)提供了?gcache?的?Redis?緩存適配實(shí)現(xiàn)。?Redis?緩存在多節(jié)點(diǎn)保證緩存的數(shù)據(jù)一致性時(shí)非常有用,特別是?Session?共享、數(shù)據(jù)庫(kù)查詢緩存等場(chǎng)景中。

使用示例

func ExampleCache_SetAdapter() {
	var (
		err         error
		ctx         = gctx.New()
		cache       = gcache.New()
		redisConfig = &gredis.Config{
			Address: "127.0.0.1:6379",
			Db:      9,
		}
		cacheKey   = `key`
		cacheValue = `value`
	)
	// Create redis client object.
	redis, err := gredis.New(redisConfig)
	if err != nil {
		panic(err)
	}
	// Create redis cache adapter and set it to cache object.
	cache.SetAdapter(gcache.NewAdapterRedis(redis))

	// Set and Get using cache object.
	err = cache.Set(ctx, cacheKey, cacheValue, time.Second)
	if err != nil {
		panic(err)
	}
	fmt.Println(cache.MustGet(ctx, cacheKey).String())

	// Get using redis client.
	fmt.Println(redis.MustDo(ctx, "GET", cacheKey).String())

	// Output:
	// value
	// value
}


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)