feat(barcode): Implement cache
This commit is contained in:
parent
850fa0a760
commit
31734596f6
@ -2,9 +2,12 @@ package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"image/png"
|
||||
"log"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/boombuler/barcode"
|
||||
"github.com/boombuler/barcode/code128"
|
||||
@ -23,10 +26,22 @@ type DefaultBarcodeService struct {
|
||||
}
|
||||
|
||||
func (b *DefaultBarcodeService) GenerateBarcode(format string, content string, width int, height int) (bytes.Buffer, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
if !b.IsTypeSupported(format) {
|
||||
return bytes.Buffer{}, fmt.Errorf("unsupported barcode type: %s", format)
|
||||
}
|
||||
|
||||
if b.RedisClient != nil {
|
||||
cachedBarcode, err := b.RedisClient.Get(ctx, fmt.Sprintf("barcode:%s:%s:%d:%d", format, content, width, height)).Result()
|
||||
if err == nil {
|
||||
log.Printf("Cache hit for barcode:%s:%s:%d:%d", format, content, width, height)
|
||||
buf := bytes.Buffer{}
|
||||
buf.Write([]byte(cachedBarcode))
|
||||
return buf, nil
|
||||
}
|
||||
}
|
||||
|
||||
var generatedCode barcode.Barcode
|
||||
var err error
|
||||
|
||||
@ -62,6 +77,13 @@ func (b *DefaultBarcodeService) GenerateBarcode(format string, content string, w
|
||||
return bytes.Buffer{}, err
|
||||
}
|
||||
|
||||
if b.RedisClient != nil {
|
||||
err = b.RedisClient.Set(ctx, fmt.Sprintf("barcode:%s:%s:%d:%d", format, content, width, height), buf.String(), 10*time.Minute).Err()
|
||||
if err != nil {
|
||||
return bytes.Buffer{}, err
|
||||
}
|
||||
}
|
||||
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user