Skip to content

Commit

Permalink
Merge pull request #25 from goravel/kkumar-gcc/#316
Browse files Browse the repository at this point in the history
feat: [#316] Redis cache support connection with TLS
  • Loading branch information
kkumar-gcc authored Jun 4, 2024
2 parents b15533e + 25788d6 commit 6896fd4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,25 @@ import (
},
```

To enable TLS/SSL, you need to add the following configuration:

```
import "crypto/tls"
// config/database.go
"redis": map[string]any{
"default": map[string]any{
"host": config.Env("REDIS_HOST", ""),
"password": config.Env("REDIS_PASSWORD", ""),
"port": config.Env("REDIS_PORT", 6379),
"database": config.Env("REDIS_DB", 0),
"tls": &tls.Config{
// Add your tls configuration here
},
},
},
```

## Testing

Run command below to run test:
Expand Down
12 changes: 10 additions & 2 deletions redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package redis

import (
"context"
"crypto/tls"
"fmt"
"strconv"
"time"
Expand Down Expand Up @@ -31,11 +32,18 @@ func NewRedis(ctx context.Context, config config.Config, store string) (*Redis,
return nil, nil
}

client := redis.NewClient(&redis.Options{
option := &redis.Options{
Addr: fmt.Sprintf("%s:%s", host, config.GetString(fmt.Sprintf("database.redis.%s.port", connection))),
Password: config.GetString(fmt.Sprintf("database.redis.%s.password", connection)),
DB: config.GetInt(fmt.Sprintf("database.redis.%s.database", connection)),
})
}

tlsConfig, ok := config.Get(fmt.Sprintf("database.redis.%s.tls", connection)).(*tls.Config)
if ok {
option.TLSConfig = tlsConfig
}

client := redis.NewClient(option)

if _, err := client.Ping(context.Background()).Result(); err != nil {
return nil, errors.WithMessage(err, "init connection error")
Expand Down
1 change: 1 addition & 0 deletions redis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ func getRedisDocker() (*dockertest.Pool, *dockertest.Resource, *Redis, error) {
mockConfig.On("GetString", "database.redis.default.port").Return(resource.GetPort("6379/tcp")).Once()
mockConfig.On("GetString", "database.redis.default.password").Return(resource.GetPort("")).Once()
mockConfig.On("GetInt", "database.redis.default.database").Return(0).Once()
mockConfig.On("Get", "database.redis.default.tls").Return(nil).Once()
mockConfig.On("GetString", "cache.prefix").Return("goravel_cache").Once()
store, err = NewRedis(context.Background(), mockConfig, "redis")

Expand Down

0 comments on commit 6896fd4

Please sign in to comment.