为 Firestore 分布式计数器创建自定义碎片和计数器类型

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

为 Firestore 分布式计数器创建自定义碎片和计数器类型

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C#

/// <summary>
/// Shard is a document that contains the count.
/// </summary>
[FirestoreData]
public class Shard
{
    [FirestoreProperty(name: "count")]
    public int Count { get; set; }
}

Go

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"

	"cloud.google.com/go/firestore"
	"google.golang.org/api/iterator"
)

// Counter is a collection of documents (shards)
// to realize counter with high frequency.
type Counter struct {
	numShards int
}

// Shard is a single counter, which is used in a group
// of other shards within Counter.
type Shard struct {
	Count int
}

Python

import random

from google.cloud import firestore

class Shard(object):
    """
    A shard is a distributed counter. Each shard can support being incremented
    once per second. Multiple shards are needed within a Counter to allow
    more frequent incrementing.
    """

    def __init__(self):
        self._count = 0

    def to_dict(self):
        return {"count": self._count}

class Counter(object):
    """
    A counter stores a collection of shards which are
    summed to return a total count. This allows for more
    frequent incrementing than a single document.
    """

    def __init__(self, num_shards):
        self._num_shards = num_shards

后续步骤

如需搜索并过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器