Skip to content

Complete Examples

This document contains comprehensive usage examples for the Redis client.

Example 1: Basic String Operations

vb
Sub Example1_BasicString()
    Dim oRedis As New cRedisClient

    ' Connect
    If Not oRedis.Connect() Then
        Debug.Print "Connection failed: " & oRedis.LastError
        Exit Sub
    End If

    ' Set values
    oRedis.Set_ "name", "Zhang San"
    oRedis.Set_ "age", "25"

    ' Get values
    Debug.Print "Name: " & oRedis.Get_("name")
    Debug.Print "Age: " & oRedis.Get_("age")

    ' Set expiration time
    oRedis.Expire "name", 300

    ' Check remaining time
    Debug.Print "name remaining TTL: " & oRedis.TTL("name") & " seconds"

    ' Disconnect
    oRedis.DisConnect
End Sub

Example 2: Hash Operations

vb
Sub Example2_HashOperations()
    Dim oRedis As New cRedisClient

    If Not oRedis.Connect() Then
        Debug.Print "Connection failed: " & oRedis.LastError
        Exit Sub
    End If

    ' Set user information
    oRedis.HSet "user:1001", "name", "Li Si"
    oRedis.HSet "user:1001", "age", "30"
    oRedis.HSet "user:1001", "city", "Shanghai"
    oRedis.HSet "user:1001", "email", "lisi@example.com"

    ' Get single field
    Debug.Print "User name: " & oRedis.HGet("user:1001", "name")

    ' Get all fields
    Dim oDict As Scripting.Dictionary
    Set oDict = oRedis.HGetAll("user:1001")

    Debug.Print vbCrLf & "User details:"
    Dim vKey As Variant
    For Each vKey In oDict.Keys
        Debug.Print "  " & vKey & ": " & oDict(vKey)
    Next

    oRedis.DisConnect
End Sub

Example 3: List Operations

vb
Sub Example3_ListOperations()
    Dim oRedis As New cRedisClient

    If Not oRedis.Connect() Then
        Debug.Print "Connection failed: " & oRedis.LastError
        Exit Sub
    End If

    ' Clear existing list
    oRedis.Del "tasks"

    ' Add tasks
    oRedis.RPush "tasks", "Task1"
    oRedis.RPush "tasks", "Task2"
    oRedis.RPush "tasks", "Task3"
    oRedis.RPush "tasks", "Task4"
    oRedis.RPush "tasks", "Task5"

    ' Get list length
    Debug.Print "Task list length: " & oRedis.lLen("tasks")

    ' Get all tasks
    Dim vTasks As Variant
    vTasks = oRedis.LRange("tasks", 0, -1)

    Debug.Print vbCrLf & "All tasks:"
    Dim i As Long
    For i = 0 To UBound(vTasks)
        Debug.Print "  " & (i + 1) & ". " & vTasks(i)
    Next

    ' Process first task
    Debug.Print vbCrLf & "Processing task: " & oRedis.LPop("tasks")
    Debug.Print "Remaining tasks: " & oRedis.lLen("tasks")

    oRedis.DisConnect
End Sub

Example 4: Transaction Operations

vb
Sub Example4_Transaction()
    Dim oRedis As New cRedisClient

    If Not oRedis.Connect() Then
        Debug.Print "Connection failed: " & oRedis.LastError
        Exit Sub
    End If

    ' Initialize counter
    oRedis.Set_ "counter", "0"
    Debug.Print "Initial count: " & oRedis.Get_("counter")

    ' Start transaction
    oRedis.Multi

    ' Execute multiple increment operations
    oRedis.Incr "counter"
    oRedis.Incr "counter"
    oRedis.Incr "counter"

    ' Commit transaction
    Dim vResults As Variant
    vResults = oRedis.Exec()

    Debug.Print "Transaction execution results:"
    If IsArray(vResults) Then
        For i = 0 To UBound(vResults)
            Debug.Print "  Operation " & (i + 1) & " result: " & vResults(i)
        Next
    End If

    Debug.Print "Final count: " & oRedis.Get_("counter")

    oRedis.DisConnect
End Sub

Example 5: Set and Sorted Set Operations

vb
Sub Example5_Sets()
    Dim oRedis As New cRedisClient

    If Not oRedis.Connect() Then
        Debug.Print "Connection failed: " & oRedis.LastError
        Exit Sub
    End If

    ' Use Set to store tags
    oRedis.SAdd "post:1:tags", "Technology", "Programming", "Redis", "VB6"

    Debug.Print "Article tags count: " & oRedis.SCard("post:1:tags")

    Dim vTags As Variant
    vTags = oRedis.SMembers("post:1:tags")

    Debug.Print "All tags:"
    Dim i As Long
    For i = 0 To UBound(vTags)
        Debug.Print "  - " & vTags(i)
    Next

    ' Use Sorted Set to store leaderboard
    oRedis.ZAdd "leaderboard", 1000, "Player A"
    oRedis.ZAdd "leaderboard", 1500, "Player B"
    oRedis.ZAdd "leaderboard", 800, "Player C"
    oRedis.ZAdd "leaderboard", 2000, "Player D"

    Debug.Print vbCrLf & "Leaderboard (sorted by score ascending):"
    vTags = oRedis.ZRange("leaderboard", 0, -1)
    For i = 0 To UBound(vTags)
        Debug.Print "  " & (i + 1) & ". " & vTags(i)
    Next

    Debug.Print vbCrLf & "Leaderboard (with scores):"
    vTags = oRedis.ZRange("leaderboard", 0, -1, True)
    For i = 0 To UBound(vTags) Step 2
        If i + 1 <= UBound(vTags) Then
            Debug.Print "  " & vTags(i) & ": " & vTags(i + 1) & " points"
        End If
    Next

    oRedis.DisConnect
End Sub

Example 6: Database Switching and Batch Operations

vb
Sub Example6_MultipleDb()
    Dim oRedis As New cRedisClient

    If Not oRedis.Connect() Then
        Debug.Print "Connection failed: " & oRedis.LastError
        Exit Sub
    End If

    ' Store user data in database 0
    oRedis.SelectDb 0
    oRedis.Set_ "user:1", "Zhang San"
    oRedis.Set_ "user:2", "Li Si"
    Debug.Print "Users in database 0: "

    Dim vKeys As Variant
    vKeys = oRedis.Keys("user:*")
    Dim i As Long
    If IsArray(vKeys) Then
        For i = 0 To UBound(vKeys)
            Debug.Print "  " & vKeys(i) & ": " & oRedis.Get_(vKeys(i))
        Next
    End If

    ' Store configuration data in database 1
    oRedis.SelectDb 1
    oRedis.Set_ "config:appname", "MyApp"
    oRedis.Set_ "config:version", "1.0.0"
    oRedis.Set_ "config:debug", "false"
    Debug.Print vbCrLf & "Configuration in database 1: "

    vKeys = oRedis.Keys("config:*")
    If IsArray(vKeys) Then
        For i = 0 To UBound(vKeys)
            Debug.Print "  " & vKeys(i) & ": " & oRedis.Get_(vKeys(i))
        Next
    End If

    ' Batch get configuration
    Dim vConfigs As Variant
    vConfigs = oRedis.MGet("config:appname", "config:version")
    Debug.Print vbCrLf & "Configuration info:"
    If IsArray(vConfigs) Then
        For i = 0 To UBound(vConfigs)
            Debug.Print "  " & vConfigs(i)
        Next
    End If

    ' Switch back to database 0
    oRedis.SelectDb 0
    Debug.Print vbCrLf & "Current database: " & oRedis.DbIndex

    oRedis.DisConnect
End Sub

Example 7: Comprehensive Application - User Session Management

vb
Sub Example7_UserSession()
    Dim oRedis As New cRedisClient

    If Not oRedis.Connect() Then
        Debug.Print "Connection failed: " & oRedis.LastError
        Exit Sub
    End If

    Dim sUserId As String
    sUserId = "user:123"

    ' Use Hash to store user information
    oRedis.HSet sUserId, "name", "Zhang San"
    oRedis.HSet sUserId, "email", "zhangsan@example.com"
    oRedis.HSet sUserId, "login_time", CStr(Now())

    ' Use Set to store user tags
    oRedis.SAdd sUserId & ":tags", "VIP", "Active", "Verified"

    ' Use List to store recent operations
    oRedis.RPush sUserId & ":history", "Login"
    oRedis.RPush sUserId & ":history", "Browse products"
    oRedis.RPush sUserId & ":history", "Add to cart"

    ' Set session expiration time (30 minutes)
    oRedis.Expire sUserId, 1800
    oRedis.Expire sUserId & ":tags", 1800
    oRedis.Expire sUserId & ":history", 1800

    ' Display user information
    Debug.Print "=== User Information ==="
    Dim oDict As Scripting.Dictionary
    Set oDict = oRedis.HGetAll(sUserId)

    Dim vKey As Variant
    For Each vKey In oDict.Keys
        Debug.Print vKey & ": " & oDict(vKey)
    Next

    ' Display user tags
    Debug.Print vbCrLf & "=== User Tags ==="
    Dim vTags As Variant
    vTags = oRedis.SMembers(sUserId & ":tags")

    For i = 0 To UBound(vTags)
        Debug.Print "- " & vTags(i)
    Next

    ' Display recent operations
    Debug.Print vbCrLf & "=== Recent Operations ==="
    Dim vHistory As Variant
    vHistory = oRedis.LRange(sUserId & ":history", -5, -1)

    For i = 0 To UBound(vHistory)
        Debug.Print (i + 1) & ". " & vHistory(i)
    Next

    oRedis.DisConnect
End Sub

Example 8: Comprehensive Application - E-commerce System

vb
Sub Example8_ECommerce()
    Dim oRedis As New cRedisClient

    If Not oRedis.Connect() Then
        Debug.Print "Connection failed: " & oRedis.LastError
        Exit Sub
    End If

    ' 1. Product information (Hash)
    Debug.Print "=== Product Information ==="
    oRedis.HSet "product:1001", "name", "iPhone 15"
    oRedis.HSet "product:1001", "price", "5999"
    oRedis.HSet "product:1001", "stock", "100"

    Debug.Print "Product: " & oRedis.HGet("product:1001", "name")
    Debug.Print "Price: ¥" & oRedis.HGet("product:1001", "price")
    Debug.Print "Stock: " & oRedis.HGet("product:1001", "stock")

    ' 2. Shopping cart (Hash)
    Debug.Print vbCrLf & "=== Shopping Cart ==="
    oRedis.HSet "cart:user123", "product:1001", "2"
    oRedis.HSet "cart:user123", "product:1002", "1"

    Dim oCart As Scripting.Dictionary
    Set oCart = oRedis.HGetAll("cart:user123")

    Dim lTotal As Long
    lTotal = 0
    For Each vKey In oCart.Keys
        Debug.Print vKey & ": " & oCart(vKey) & " items"
        lTotal = lTotal + CLng(oCart(vKey))
    Next
    Debug.Print "Total items: " & lTotal

    ' 3. Hot products (Sorted Set)
    Debug.Print vbCrLf & "=== Hot Products ==="
    oRedis.ZAdd "hot:products", 100, "product:1001"
    oRedis.ZAdd "hot:products", 80, "product:1002"
    oRedis.ZAdd "hot:products", 150, "product:1003"

    Dim vHot As Variant
    vHot = oRedis.ZRange("hot:products", -3, -1)

    For i = UBound(vHot) To 0 Step -1
        Dim sProductId As String
        sProductId = vHot(i)
        Debug.Print (UBound(vHot) - i + 1) & ". " & oRedis.HGet(sProductId, "name")
    Next

    ' 4. Order queue (List)
    Debug.Print vbCrLf & "=== Order Queue ==="
    oRedis.RPush "orders:pending", "ORDER001: " & Now()
    oRedis.RPush "orders:pending", "ORDER002: " & Now()

    Dim vOrders As Variant
    vOrders = oRedis.LRange("orders:pending", 0, -1)

    For i = 0 To UBound(vOrders)
        Debug.Print vOrders(i)
    Next

    ' 5. User tags (Set)
    Debug.Print vbCrLf & "=== User Tags ==="
    oRedis.SAdd "user:123:tags", "VIP", "Active", "New user"
    vTags = oRedis.SMembers("user:123:tags")

    For i = 0 To UBound(vTags)
        Debug.Print "- " & vTags(i)
    Next

    oRedis.DisConnect
End Sub

Example 9: Error Handling

vb
Sub Example9_ErrorHandling()
    Dim oRedis As New cRedisClient

    ' Connect
    If Not oRedis.Connect() Then
        Debug.Print "Connection failed: " & oRedis.LastError
        Exit Sub
    End If

    ' Check for errors
    If oRedis.LastError <> "" Then
        Debug.Print "Connection error: " & oRedis.LastError
        oRedis.DisConnect
        Exit Sub
    End If

    ' Execute operations
    oRedis.Set_ "test", "value"

    If oRedis.LastError <> "" Then
        Debug.Print "Operation error: " & oRedis.LastError
    Else
        Debug.Print "Operation successful"
    End If

    ' Get non-existent key
    Dim sValue As String
    sValue = oRedis.Get_("nonexistent")

    If sValue = "" Then
        Debug.Print "Key does not exist"
    End If

    oRedis.DisConnect
End Sub

Example 10: Connection Management Best Practices

vb
Sub Example10_ConnectionManagement()
    Dim oRedis As cRedisClient
    Set oRedis = New cRedisClient

    ' Connect
    If Not oRedis.Connect() Then
        Debug.Print "Connection failed: " & oRedis.LastError
        GoTo Cleanup
    End If

    ' Use connection
    oRedis.Set_ "key", "value"
    Debug.Print "Set value: " & oRedis.Get_("key")

Cleanup:
    ' Ensure disconnection
    If Not oRedis Is Nothing Then
        If oRedis.Connected Then
            oRedis.DisConnect
        End If
        Set oRedis = Nothing
    End If
End Sub

Running Examples

You can copy the above code directly into a VB6 or VBA environment. Ensure:

  1. Added reference to cRedisClient class
  2. Added reference to Scripting.Dictionary (Microsoft Scripting Runtime)
  3. Redis server is running and accessible

Example Output

After running the above examples, you will see similar output in the Immediate Window:

=== User Information ===
name: Zhang San
email: zhangsan@example.com
login_time: 2024-01-01 10:30:00

=== User Tags ===
- VIP
- Active
- Verified

=== Recent Operations ===
1. Login
2. Browse products
3. Add to cart

More Examples

For more specific scenario examples, please refer to:

VB6 and LOGO copyright of Microsoft Corporation