counter

fun counter(documentId: String, common: CommonOptions = CommonOptions.Default, durability: Durability = Durability.none(), expiry: Expiry = Expiry.none()): Counter

Returns a counter backed by a document on the server.

Samples

import com.couchbase.client.kotlin.Collection
import com.couchbase.client.kotlin.kv.Expiry
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.time.Duration.Companion.seconds
fun main() { 
   //sampleStart 
   // Limiting the rate of requests using an expiring counter.

val requestLimit = 2u
val period = 3.seconds
val counter = collection.counter("requests", expiry = Expiry.of(period))

runBlocking {
    repeat(30) {
        // simulate the arrival of a request
        val requestCount = counter.incrementAndGet()

        if (requestCount > requestLimit) {
            println("REJECTING request; received more than $requestLimit requests in $period")
        } else {
            println("servicing request $requestCount in this period")
        }

        delay(1000)
    }
    println("done")
} 
   //sampleEnd
}
import com.couchbase.client.kotlin.Collection
import com.couchbase.client.kotlin.kv.Expiry
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.time.Duration.Companion.seconds
fun main() { 
   //sampleStart 
   // Generate unique document IDs using a counter.

// Include the name of the current datacenter to ensure IDs are
// globally unique when using Cross-Datacenter Replication (XDCR).
val datacenter = "dc1"

val idCounter = collection.counter("widgetIdCounter-$datacenter")

runBlocking {
    for (i in 1..5) {
        val docId = "widget-${datacenter}-${idCounter.incrementAndGet()}"
        println(docId)
        collection.insert(docId, content = "My ID is $docId")
    }
} 
   //sampleEnd
}

Parameters

documentId

the ID of the document to hold the counter value

expiry

how long the counter document should exist before the counter is reset. The expiry param is ignored if the counter document already exists.

durability

durability requirements for counter operations