github.com/rosedblabs/rosedb/v2@v2.3.7-0.20240423093736-a89ea823e5b9/examples/watch/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/rosedblabs/rosedb/v2"
     8  	"github.com/rosedblabs/rosedb/v2/utils"
     9  )
    10  
    11  // this file shows how to use the Watch feature of rosedb.
    12  
    13  func main() {
    14  	// specify the options
    15  	options := rosedb.DefaultOptions
    16  	options.DirPath = "/tmp/rosedb_watch"
    17  	options.WatchQueueSize = 1000
    18  
    19  	// open a database
    20  	db, err := rosedb.Open(options)
    21  	if err != nil {
    22  		panic(err)
    23  	}
    24  	defer func() {
    25  		_ = db.Close()
    26  	}()
    27  
    28  	// run a new goroutine to handle db event.
    29  	go func() {
    30  		eventCh, err := db.Watch()
    31  		if err != nil {
    32  			return
    33  		}
    34  		for {
    35  			event := <-eventCh
    36  			// when db closed, the event will receive nil.
    37  			if event == nil {
    38  				fmt.Println("The db is closed, so the watch channel is closed.")
    39  				return
    40  			}
    41  			// events can be captured here for processing
    42  			fmt.Printf("Get a new event: key%s \n", event.Key)
    43  		}
    44  	}()
    45  
    46  	// write some data
    47  	for i := 0; i < 10; i++ {
    48  		_ = db.Put(utils.GetTestKey(i), utils.RandomValue(64))
    49  	}
    50  	// delete some data
    51  	for i := 0; i < 10/2; i++ {
    52  		_ = db.Delete(utils.GetTestKey(i))
    53  	}
    54  
    55  	// wait for watch goroutine to finish.
    56  	time.Sleep(1 * time.Second)
    57  }