optimisticLockingExample demonstrates using SetIFDEQ for optimistic locking
(ctx context.Context, rdb *redis.Client)
| 85 | |
| 86 | // optimisticLockingExample demonstrates using SetIFDEQ for optimistic locking |
| 87 | func 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 |
| 123 | func detectChangesExample(ctx context.Context, rdb *redis.Client) { |