MCPcopy
hub / github.com/redis/go-redis / optimisticLockingExample

Function optimisticLockingExample

example/digest-optimistic-locking/main.go:87–120  ·  view source on GitHub ↗

optimisticLockingExample demonstrates using SetIFDEQ for optimistic locking

(ctx context.Context, rdb *redis.Client)

Source from the content-addressed store, hash-verified

85
86// optimisticLockingExample demonstrates using SetIFDEQ for optimistic locking
87func optimisticLockingExample(ctx context.Context, rdb *redis.Client) {
88 key := "counter"
89
90 // Initial value
91 rdb.Set(ctx, key, "100", 0)
92 fmt.Printf("Initial value: %s\n", rdb.Get(ctx, key).Val())
93
94 // Get current digest
95 currentDigest := rdb.Digest(ctx, key).Val()
96 fmt.Printf("Current digest: 0x%016x\n", currentDigest)
97
98 // Simulate some processing time
99 time.Sleep(100 * time.Millisecond)
100
101 // Try to update only if value hasn't changed (digest matches)
102 newValue := "150"
103 result := rdb.SetIFDEQ(ctx, key, newValue, currentDigest, 0)
104
105 if result.Err() == redis.Nil {
106 fmt.Println("✗ Update failed: value was modified by another client")
107 } else if result.Err() != nil {
108 fmt.Printf("✗ Error: %v\n", result.Err())
109 } else {
110 fmt.Printf("✓ Update successful! New value: %s\n", rdb.Get(ctx, key).Val())
111 }
112
113 // Try again with wrong digest (simulating concurrent modification)
114 wrongDigest := uint64(12345)
115 result = rdb.SetIFDEQ(ctx, key, "200", wrongDigest, 0)
116
117 if result.Err() == redis.Nil {
118 fmt.Println("✓ Correctly rejected update with wrong digest")
119 }
120}
121
122// detectChangesExample demonstrates using SetIFDNE to detect if a value changed
123func detectChangesExample(ctx context.Context, rdb *redis.Client) {

Callers 1

mainFunction · 0.85

Calls 7

SetMethod · 0.65
PrintfMethod · 0.65
GetMethod · 0.65
DigestMethod · 0.65
SetIFDEQMethod · 0.65
ErrMethod · 0.65
ValMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…