implement redis inventory with threadsafe reservation
This commit is contained in:
@@ -2,8 +2,9 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"git.tornberg.me/go-cart-actor/pkg/inventory"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/redis/go-redis/v9/maintnotifications"
|
||||
)
|
||||
@@ -18,24 +19,36 @@ func main() {
|
||||
Mode: maintnotifications.ModeDisabled,
|
||||
},
|
||||
})
|
||||
|
||||
err := rdb.Set(ctx, "key", "value", 0).Err()
|
||||
s, err := inventory.NewRedisInventoryService(rdb, ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
log.Fatalf("Unable to connect to inventory redis", err)
|
||||
return
|
||||
}
|
||||
|
||||
val, err := rdb.Get(ctx, "key").Result()
|
||||
rdb.Pipelined(ctx, func(p redis.Pipeliner) error {
|
||||
s.UpdateInventory(p, "1", "1", 10)
|
||||
s.UpdateInventory(p, "2", "2", 20)
|
||||
s.UpdateInventory(p, "3", "3", 30)
|
||||
s.UpdateInventory(p, "4", "4", 40)
|
||||
return nil
|
||||
})
|
||||
err = s.ReserveInventory(inventory.ReserveRequest{
|
||||
SKU: "1",
|
||||
LocationID: "1",
|
||||
Quantity: 3,
|
||||
}, inventory.ReserveRequest{
|
||||
SKU: "2",
|
||||
LocationID: "2",
|
||||
Quantity: 15,
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
log.Printf("Unable to reserve inventory: %v", err)
|
||||
return
|
||||
}
|
||||
fmt.Println("key", val)
|
||||
v, err := s.GetInventory("1", "1")
|
||||
if err != nil {
|
||||
log.Printf("Unable to get inventory: %v", err)
|
||||
return
|
||||
}
|
||||
log.Printf("Inventory after reservation: %v", v)
|
||||
|
||||
val2, err := rdb.Get(ctx, "key2").Result()
|
||||
if err == redis.Nil {
|
||||
fmt.Println("key2 does not exist")
|
||||
} else if err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
fmt.Println("key2", val2)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user