|
17 | 17 | package StarterGoRedis |
18 | 18 |
|
19 | 19 | import ( |
| 20 | + "github.com/go-spring/spring-core/conf" |
20 | 21 | "github.com/go-spring/spring-core/gs" |
21 | 22 | "github.com/redis/go-redis/v9" |
22 | 23 | ) |
23 | 24 |
|
| 25 | +// Config defines Redis connection configuration. |
24 | 26 | type Config struct { |
25 | 27 | Addr string `value:"${addr}"` |
26 | 28 | Password string `value:"${password:=}"` |
27 | 29 | } |
28 | 30 |
|
| 31 | +// Factory defines an interface for creating Redis clients. |
| 32 | +type Factory interface { |
| 33 | + CreateClient(c Config) (*redis.Client, error) |
| 34 | +} |
| 35 | + |
| 36 | +type DefaultFactory struct{} |
| 37 | + |
| 38 | +// CreateClient creates a new Redis client based on the provided configuration. |
| 39 | +func (DefaultFactory) CreateClient(c Config) (*redis.Client, error) { |
| 40 | + return redis.NewClient(&redis.Options{ |
| 41 | + Addr: c.Addr, |
| 42 | + Password: c.Password, |
| 43 | + }), nil |
| 44 | +} |
| 45 | + |
29 | 46 | func init() { |
30 | | - gs.Group("${spring.go-redis}", |
31 | | - func(c Config) (*redis.Client, error) { // init |
32 | | - return redis.NewClient(&redis.Options{ |
33 | | - Addr: c.Addr, |
34 | | - Password: c.Password, |
35 | | - }), nil |
36 | | - }, |
37 | | - func(client *redis.Client) error { // destroy |
38 | | - return client.Close() |
39 | | - }) |
| 47 | + const key = "spring.go-redis" |
| 48 | + |
| 49 | + // Register a module that initializes Redis clients |
| 50 | + gs.Module([]gs.ConditionOnProperty{ |
| 51 | + gs.OnProperty(key), |
| 52 | + }, func(p conf.Properties) error { |
| 53 | + |
| 54 | + // Bind configuration into a map of name -> Config |
| 55 | + var m map[string]Config |
| 56 | + if err := p.Bind(&m, "${"+key+"}"); err != nil { |
| 57 | + return err |
| 58 | + } |
| 59 | + |
| 60 | + // Register DefaultFactory as a bean implementing Factory, |
| 61 | + // but only if no other Factory bean has been provided. |
| 62 | + gs.Object(&DefaultFactory{}). |
| 63 | + Condition(gs.OnMissingBean[Factory]()). |
| 64 | + Export(gs.As[Factory]()) |
| 65 | + |
| 66 | + // For each Redis configuration entry, |
| 67 | + // create and register a Redis client bean. |
| 68 | + for name, c := range m { |
| 69 | + gs.Provide(func(factory Factory) (*redis.Client, error) { // create |
| 70 | + return factory.CreateClient(c) |
| 71 | + }).Destroy(func(client *redis.Client) error { // destroy |
| 72 | + return client.Close() |
| 73 | + }).Name(name) |
| 74 | + } |
| 75 | + return nil |
| 76 | + }) |
40 | 77 | } |
0 commit comments