举报投诉联系我们 手机版 热门标签 名动网
您的位置:名动网 > gorm redis缓存 GoFrame 缓存管理-Redis缓存

gorm redis缓存 GoFrame 缓存管理-Redis缓存

2023-06-16 21:20 GoFrame教程

gorm redis缓存 GoFrame 缓存管理-Redis缓存

gorm redis缓存

GORM Redis缓存是一种高性能的内存数据库,它可以将数据存储在内存中,从而提高数据库的访问速度。GORM Redis缓存可以帮助开发者快速获取和保存数据,减少对数据库的负载。

GORM Redis缓存主要由三部分组成:Redis服务器、GORM客户端和Redis客户端。Redis服务器是一个开源的内存数据库,它可以将数据快速地存储在内存中;GORM客户端是一个由Go语言开发的高性能ORM工具;Redis客户端是一个由Go语言开发的Redis连接工具。

// 创建 Gorm Redis 缓存
cache := gormrediscache.New(redis.NewClient(&redis.Options{
    Addr:     "localhost:6379", // Redis 服务器地址
    Password: "",               // Redis 服务器密码 
    DB:       0,                // 数据库 ID 
})) 

使用 Gorm Redis 缓存时,首先要创建一个 Gorm Redis 的实例,然后将其传递给 Gorm 函数。这样就可以使用 Gorm 来读写 Redis 数据库了。此外,Gorm 还可以使用多种不同的方法来读写 Redis 数据库,例如 Get、Set、Delete 等方法。

 
// 获取 key 对应的 value  
value, err := cache.Get("key")  
if err != nil {  									  	  	  	  	  	  	  	  	     return err  }  // 设置 key 和 value    err = cache.Set("key", "value")    if err != nil {     return err } 

此外,Gorm 还可以使用 TTL 来自动删除过期的 key-value 键值对。TTL 参数表示 key-value 键值对在多长时间后过期并被删除。当 TTL 超时时,Gorm 可以根据 TTL 的时间来删除相关 key-value 键值对。

// 自动删除过期 key-value 键值对    err = cache.SetWithTTL("key", "value", time.Second*10)    if err != nil {     return err } 

总之,GORM Redis 的优势在于能够快速读写大量数据并提供良好的性能表现。使用 GORM Redis 的开发者不但能够减少对原始数据库的负载,而且还能够快速地读写大量数据并提供优化后的性能表现。

GoFrame 缓存管理-Redis缓存

基本介绍

缓存组件同时提供了​gcache​的​Redis​缓存适配实现。​Redis​缓存在多节点保证缓存的数据一致性时非常有用,特别是​Session​共享、数据库查询缓存等场景中。

使用示例

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
}


阅读全文
以上是名动网为你收集整理的gorm redis缓存 GoFrame 缓存管理-Redis缓存全部内容。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
相关文章
© 2024 名动网 mdwl.vip 版权所有 联系我们