Skip to content

Commit df6d4a8

Browse files
committed
Merge branch 'main' into feature/26-mongo-advanced-config
2 parents fc2243e + 2179013 commit df6d4a8

File tree

10 files changed

+2058
-3
lines changed

10 files changed

+2058
-3
lines changed
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
# Hystrix Factory
2+
3+
## Overview
4+
5+
The Hystrix Factory provides integration with the [Hystrix-Go](https://github.com/afex/hystrix-go) library, implementing the circuit breaker pattern for Go applications within the Boost framework. This factory enables resilient and fault-tolerant systems by preventing cascading failures in distributed environments.
6+
7+
## Features
8+
9+
- **Command Configuration**: Easy configuration of Hystrix commands through Boost's configuration system
10+
- **Circuit Breaker Pattern**: Implementation of the circuit breaker pattern to handle failures gracefully
11+
- **Configurable Parameters**: Fine-grained control over timeout, concurrency, error thresholds, and recovery windows
12+
- **Logging Integration**: Seamless integration with Boost's logging system
13+
14+
## Usage
15+
16+
### Basic Configuration
17+
18+
```go
19+
package main
20+
21+
import (
22+
"github.com/xgodev/boost"
23+
"github.com/xgodev/boost/factory/contrib/afex/hystrix-go/v0"
24+
)
25+
26+
func main() {
27+
// Initialize Boost
28+
boost.Start()
29+
30+
// Configure a Hystrix command
31+
hystrix.ConfigureCommand("my_command")
32+
33+
// Use the command in your application
34+
// ...
35+
}
36+
```
37+
38+
### Configuring Multiple Commands
39+
40+
```go
41+
// Configure multiple commands at once
42+
commands := []string{"database_query", "api_request", "authentication"}
43+
hystrix.ConfigureCommands(commands)
44+
```
45+
46+
### Custom Configuration
47+
48+
You can customize Hystrix command parameters through Boost's configuration system:
49+
50+
```
51+
# In your configuration file or environment variables
52+
boost.factory.hystrix.commands.my_command.timeout=5000
53+
boost.factory.hystrix.commands.my_command.maxConcurrentRequests=10
54+
boost.factory.hystrix.commands.my_command.requestVolumeThreshold=20
55+
boost.factory.hystrix.commands.my_command.errorPercentThreshold=25
56+
boost.factory.hystrix.commands.my_command.sleepWindow=10000
57+
```
58+
59+
## Configuration Parameters
60+
61+
| Parameter | Description | Default |
62+
|-----------|-------------|---------|
63+
| `timeout` | How long to wait for command to complete (milliseconds) | 10000 |
64+
| `maxConcurrentRequests` | Maximum number of concurrent requests | 20 |
65+
| `requestVolumeThreshold` | Minimum requests needed before circuit can trip | 10 |
66+
| `errorPercentThreshold` | Error percentage to open the circuit | 5 |
67+
| `sleepWindow` | Time to wait after circuit opens before testing recovery (milliseconds) | 5000 |
68+
69+
## Integration with Other Boost Components
70+
71+
The Hystrix Factory integrates with:
72+
73+
- **Config Wrapper**: For loading and managing configuration
74+
- **Log Wrapper**: For logging circuit breaker events and errors
75+
76+
## Plugin System
77+
78+
The factory supports plugins for extending functionality. Custom plugins can be added to the `plugins` directory and registered with the factory.
79+
80+
## Example
81+
82+
```go
83+
package main
84+
85+
import (
86+
"errors"
87+
"github.com/afex/hystrix-go/hystrix"
88+
hystrixfactory "github.com/xgodev/boost/factory/contrib/afex/hystrix-go/v0"
89+
"github.com/xgodev/boost/wrapper/log"
90+
)
91+
92+
func main() {
93+
// Configure the command
94+
hystrixfactory.ConfigureCommand("get_user_profile")
95+
96+
// Use the command
97+
err := hystrix.Do("get_user_profile", func() error {
98+
// This function will be executed if the circuit is closed
99+
return callExternalService()
100+
}, func(err error) error {
101+
// This function will be executed if the circuit is open
102+
log.Errorf("Circuit open, using fallback: %v", err)
103+
return getFallbackUserProfile()
104+
})
105+
106+
if err != nil {
107+
log.Errorf("Error: %v", err)
108+
}
109+
}
110+
111+
func callExternalService() error {
112+
// Actual implementation to call external service
113+
return nil
114+
}
115+
116+
func getFallbackUserProfile() error {
117+
// Fallback implementation
118+
return errors.New("using cached profile")
119+
}
120+
```
121+
122+
## Best Practices
123+
124+
1. **Command Naming**: Use descriptive names for commands that reflect their purpose
125+
2. **Timeout Configuration**: Set appropriate timeouts based on expected response times
126+
3. **Error Thresholds**: Adjust error thresholds based on your application's tolerance for failures
127+
4. **Monitoring**: Monitor circuit breaker states to understand system health
128+
129+
## References
130+
131+
- [Hystrix-Go GitHub Repository](https://github.com/afex/hystrix-go)
132+
- [Circuit Breaker Pattern](https://martinfowler.com/bliki/CircuitBreaker.html)
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
# BigCache Factory
2+
3+
## Overview
4+
5+
The BigCache Factory provides integration with the [BigCache](https://github.com/allegro/bigcache) library, a fast, concurrent, evicting in-memory cache designed for high-load applications. This factory enables efficient caching capabilities within the Boost framework, optimized for applications that require high performance with minimal GC overhead.
6+
7+
## Features
8+
9+
- **In-Memory Caching**: Fast access to cached data with minimal latency
10+
- **Configurable Eviction**: Time-based eviction policies with customizable life windows
11+
- **Sharded Architecture**: Concurrent access with minimal lock contention
12+
- **Memory Management**: Hard limits on cache size to prevent memory issues
13+
- **Metrics & Statistics**: Optional statistics collection for monitoring
14+
- **Logging Integration**: Seamless integration with Boost's logging system
15+
16+
## Usage
17+
18+
### Basic Usage
19+
20+
```go
21+
package main
22+
23+
import (
24+
"context"
25+
"github.com/xgodev/boost"
26+
"github.com/xgodev/boost/factory/contrib/allegro/bigcache/v3"
27+
"github.com/xgodev/boost/wrapper/log"
28+
)
29+
30+
func main() {
31+
// Initialize Boost
32+
boost.Start()
33+
34+
// Create a context with logger
35+
ctx := log.WithLogger(context.Background(), log.GetLogger())
36+
37+
// Create a new cache with default settings
38+
cache, err := bigcache.NewCache(ctx)
39+
if err != nil {
40+
log.Errorf("Failed to create cache: %v", err)
41+
return
42+
}
43+
44+
// Use the cache
45+
cache.Set("key", []byte("value"))
46+
entry, err := cache.Get("key")
47+
if err != nil {
48+
log.Errorf("Failed to get entry: %v", err)
49+
}
50+
51+
log.Infof("Retrieved value: %s", string(entry))
52+
}
53+
```
54+
55+
### Custom Configuration
56+
57+
You can customize BigCache parameters through Boost's configuration system:
58+
59+
```go
60+
// Create a cache with custom configuration path
61+
cache, err := bigcache.NewCacheWithConfigPath(ctx, "myapp.cache")
62+
if err != nil {
63+
log.Errorf("Failed to create cache: %v", err)
64+
return
65+
}
66+
```
67+
68+
Or by directly providing options:
69+
70+
```go
71+
// Create options and modify them
72+
options, err := bigcache.NewOptions()
73+
if err != nil {
74+
log.Errorf("Failed to create options: %v", err)
75+
return
76+
}
77+
78+
// Customize options
79+
options.Shards = 2048
80+
options.LifeWindow = 10 * time.Minute
81+
options.HardMaxCacheSize = 512 // MB
82+
83+
// Create cache with custom options
84+
cache, err := bigcache.NewCacheWithOptions(ctx, options)
85+
if err != nil {
86+
log.Errorf("Failed to create cache: %v", err)
87+
return
88+
}
89+
```
90+
91+
## Configuration Parameters
92+
93+
| Parameter | Description | Default |
94+
|-----------|-------------|---------|
95+
| `shards` | Number of cache shards (must be a power of two) | 1024 |
96+
| `lifeWindow` | Time after which entry can be evicted | 5 minutes |
97+
| `cleanWindow` | Interval between removing expired entries | 0 (disabled) |
98+
| `maxEntriesInWindow` | Max number of entries in life window | 600,000 |
99+
| `maxEntrySize` | Max size of entry in bytes | 1 MB |
100+
| `verbose` | Verbose mode for memory allocation information | false |
101+
| `hardMaxCacheSize` | Limit for cache size in MB (0 = unlimited) | 1 |
102+
| `statsEnabled` | Enable statistics collection | false |
103+
104+
## Integration with Other Boost Components
105+
106+
The BigCache Factory integrates with:
107+
108+
- **Config Wrapper**: For loading and managing configuration
109+
- **Log Wrapper**: For logging cache events and errors
110+
- **Context**: For propagating logger and other values
111+
112+
## Best Practices
113+
114+
1. **Shard Count**: Set the number of shards based on your expected concurrency level. Higher concurrency requires more shards to reduce lock contention.
115+
116+
2. **Life Window**: Choose an appropriate life window based on your data freshness requirements. Shorter windows reduce memory usage but may cause more cache misses.
117+
118+
3. **Entry Size**: Set the max entry size based on your typical cached objects. Setting it too high wastes memory, while setting it too low causes errors when storing larger objects.
119+
120+
4. **Memory Management**: Use `hardMaxCacheSize` to prevent the cache from consuming too much memory, especially in memory-constrained environments.
121+
122+
5. **Clean Window**: Enable periodic cleanup (by setting a positive `cleanWindow` value) for long-running applications to ensure memory is reclaimed.
123+
124+
## Performance Considerations
125+
126+
- BigCache is optimized for high-load scenarios with minimal GC overhead
127+
- The cache performs best with a large number of small entries
128+
- For very large objects, consider using a different caching solution
129+
- Monitor cache statistics in production to fine-tune parameters
130+
131+
## References
132+
133+
- [BigCache GitHub Repository](https://github.com/allegro/bigcache)
134+
- [Boost Framework Documentation](https://github.com/xgodev/boost)

0 commit comments

Comments
 (0)