# redis

Detailed example reference[here](https://github.com/asjard/asjard/blob/develop/_examples/svc-example/services/user.go)

## configuration

> than[global configuration](https://asjard.gitbook.io/docs/en/components/cache)more`client`redis client configuration

```yaml
## Cache related configuration
asjard:
  cache:
    ## Redis cache related configuration
    ## If not configured, inherits asjard.cache
    redis:
      ## Redis client
      ## asjard.stores.redis.clients.{the name here}
      # client: default
```

## use

```go

// Bootstrap cache initialization
func (model *ExampleModel) Bootstrap() (err error) {
	localCache, err := cache.NewLocalCache(model.ExampleTable)
	if err != nil {
		return err
	}
	// Redis cache initialization, local cache serves as the data source for redis cache
	// First get the local cache, if it doesn't exist then get the redis cache, if neither exists then get from the database
	model.kvCache, err = redis.NewKeyValueCache(model.ExampleTable,
		redis.WithLocalCache(localCache))
	if err != nil {
		return err
	}
	return nil
}

func (model *ExampleModel) Update(ctx context.Context, in *pb.CreateOrUpdateReq) (*pb.ExampleInfo, error) {
	if err := model.SetData(ctx,
		// Delete the cache key and all cache keys under the group
		model.kvCache.WithGroup(model.searchGroup()).WithKey(model.getCacheKey(in.Name)),
		func() error {
			if _, err := model.ExampleTable.Update(ctx, in); err != nil {
				return err
			}
			return nil
		}); err != nil {
		return nil, err
	}
	return model.Get(ctx, &pb.ReqWithName{Name: in.Name})
}

func (model *ExampleModel) Search(ctx context.Context, in *pb.SearchReq) (*pb.ExampleList, error) {
	var result pb.ExampleList
	if err := model.GetData(ctx, &result,
		// Retrieve via redis cache
		// And add the cache key to a group
		model.kvCache.WithKey(model.searchCacheKey(in)).WithGroup(model.searchGroup()),
		func() (any, error) {
			return model.ExampleTable.Search(ctx, in)
		}); err != nil {
		return nil, err
	}
	return &result, nil
}
```
