cmap

package module
v0.0.0-...-3befdd1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 20, 2025 License: Apache-2.0 Imports: 21 Imported by: 1

README

CMap - 高性能并发安全哈希表

Go Version License Go Report Card GoDoc Tests Coverage

一个高性能的并发安全哈希表,完全兼容 gods 库的接口设计,支持泛型和多种配置选项。

✨ 特性

  • 🔒 完全并发安全 - 通过分片技术实现高并发访问
  • 🚀 高性能 - 在并发场景下性能显著优于标准 map + 互斥锁
  • 🔧 完全兼容 Gods - 直接使用 gods 库的 Map 接口,无缝集成
  • 🎯 泛型支持 - 完全支持 Go 1.21+ 泛型
  • 📊 多种Map类型 - 支持 HashMap, TreeMap, LinkedHashMap
  • 💾 序列化支持 - 支持 JSON, JSONiter, Sonic, Gob 序列化格式
  • 📁 文件操作 - 支持保存到文件和从文件加载
  • ⚙️ 可配置 - 支持分片数量、Map类型、序列化格式等配置
  • 🧪 全面测试 - 包含单元测试、并发测试和性能基准测试

📈 性能表现(TODO)

  • TODO

🚀 快速开始

安装
go get -u github.com/Lofanmi/cmap
基本使用
package main

import (
    "fmt"
	
    "github.com/Lofanmi/cmap"
)

func main() {
    // 创建并发映射
    cm := cmap.New[string, int]()
    
    // 设置值
    cm.Put("apple", 5)
    cm.Put("banana", 3)
    
    // 获取值
    if value, found := cm.Get("apple"); found {
        fmt.Printf("苹果数量: %d\n", value)
    }
    
    fmt.Printf("总大小: %d\n", cm.Size())
}
配置选项
// 创建带配置的并发映射
cm := cmap.New[string, int](
    cmap.WithShardCount(64),          // 64个分片
    cmap.WithSerializer(cmap.JsonSerializer()), // JSON序列化
)

📚 使用场景

1. 高并发 Web 服务
// 用户会话存储
sessionStore := cmap.New[string, *UserSession]()
go func() {
    for {
        session := getUserSession()
        sessionStore.Put(session.ID, session)
    }
}()

// 多个 goroutine 同时读取
go func() {
    for {
        if session, found := sessionStore.Get(sessionID); found {
            processSession(session)
        }
    }
}()
2. 缓存系统
// 分布式缓存
cache := cmap.New[string, interface{}](cmap.WithShardCount(256))
cache.Put("user:123", userData)
cache.Put("product:456", productData)

// 批量操作
keys := []string{"user:123", "product:456", "order:789"}
results := cache.GetMultiple(keys)
3. 实时数据处理
// 实时指标收集
metrics := cmap.New[string, float64]()
for _, metric := range incomingMetrics {
    metrics.Put(metric.Name, metric.Value)
}

// 定期聚合
go func() {
    for {
        time.Sleep(time.Minute)
        aggregateMetrics(metrics)
    }
}()

🔧 API 参考

构造函数
// 通用构造函数
func New[K comparable, V any](options ...Option) *Map[K, V]

// String 键专用构造函数
func NewStringHashMap[V any](options ...Option) *Map[string, V]
func NewStringTreeMap[V any](options ...Option) *Map[string, V]
func NewStringLinkedHashMap[V any](options ...Option) *Map[string, V]

// Int 键专用构造函数
func NewIntHashMap[V any](options ...Option) *Map[int, V]
func NewIntTreeMap[V any](options ...Option) *Map[int, V]
func NewIntLinkedHashMap[V any](options ...Option) *Map[int, V]

// Int64 键专用构造函数
func NewInt64HashMap[V any](options ...Option) *Map[int64, V]
func NewInt64TreeMap[V any](options ...Option) *Map[int64, V]
func NewInt64LinkedHashMap[V any](options ...Option) *Map[int64, V]

// 通用类型构造函数
func NewHashMap[K comparable, V any](options ...Option) *Map[K, V]
func NewTreeMap[K comparable, V any](options ...Option) *Map[K, V]
func NewLinkedHashMap[K comparable, V any](options ...Option) *Map[K, V]
配置选项
func WithShardCount(count uint32) Option
func WithSerializer(serializer *SerializerFunc) Option
核心方法
// 基本操作
Put(key K, value V)
Get(key K) (value V, found bool)
Remove(key K)
Size() int
Empty() bool
Clear()

// 批量操作
PutAll(data map[K]V)
GetMultiple(keys []K) map[K]V
RemoveMultiple(keys []K)

// 序列化
MarshalJSON() ([]byte, error)
UnmarshalJSON(data []byte) error
MarshalWith(serializer *SerializerFunc) ([]byte, error)
UnmarshalWith(data []byte, serializer *SerializerFunc) error

// 文件操作
SaveToFile(filename string) error
LoadFromFile(filename string) error

// 迭代
Keys() []K
Values() []V

⚡ 性能优化建议

1. 分片数量调优
// 高并发场景
highConcurrencyMap := cmap.New[string, int](cmap.WithShardCount(512))

// 低并发场景
lowConcurrencyMap := cmap.New[string, int](cmap.WithShardCount(16))
2. 选择合适的 Map 类型
// 需要排序的场景
sortedMap := cmap.NewTreeMap[string, int]()

// 需要保持插入顺序的场景
orderedMap := cmap.NewLinkedHashMap[string, int]()

// 一般场景(推荐)
hashMap := cmap.New[string, int]()
3. 批量操作优化
// 批量添加(推荐)
data := make(map[string]int, 1000)
for i := 0; i < 1000; i++ {
    data[fmt.Sprintf("key%d", i)] = i
}
cm.PutAll(data)

// 批量获取(推荐)
keys := make([]string, 100)
for i := 0; i < 100; i++ {
    keys[i] = fmt.Sprintf("key%d", i)
}
results := cm.GetMultiple(keys)

🧪 测试

运行所有测试
go test -v
运行基准测试
go test -bench=. -benchmem
运行并发测试
go test -v -run TestConcurrent

🤝 贡献

欢迎贡献代码!请遵循以下步骤:

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开 Pull Request

📄 许可证

本项目采用 Apache License Version 2.0 许可证 - 查看 LICENSE 文件了解详情。


⭐ 如果这个项目对您有帮助,请给它一个星标!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type JSONCompatible

type JSONCompatible interface {
	IsJSON() bool
}

JSONCompatible 标记支持JSON序列化的接口

type Map

type Map[K cmp.Ordered, V any] struct {
	// contains filtered or unexported fields
}

Map 并发安全的Map实现

func New

func New[K cmp.Ordered, V any](options ...Option) *Map[K, V]

New 创建默认的并发映射(使用HashMap作为底层实现)

func NewHashMap

func NewHashMap[K cmp.Ordered, V any](options ...Option) *Map[K, V]

NewHashMap 创建HashMap类型的并发映射

func NewInt64HashMap

func NewInt64HashMap[V any](options ...Option) *Map[int64, V]

NewInt64HashMap 创建使用int64键的HashMap

func NewInt64LinkedHashMap

func NewInt64LinkedHashMap[V any](options ...Option) *Map[int64, V]

NewInt64LinkedHashMap 创建使用int64键的LinkedHashMap

func NewInt64TreeMap

func NewInt64TreeMap[V any](options ...Option) *Map[int64, V]

NewInt64TreeMap 创建使用int64键的TreeMap

func NewIntHashMap

func NewIntHashMap[V any](options ...Option) *Map[int, V]

NewIntHashMap 创建使用int键的HashMap

func NewIntLinkedHashMap

func NewIntLinkedHashMap[V any](options ...Option) *Map[int, V]

NewIntLinkedHashMap 创建使用int键的LinkedHashMap

func NewIntTreeMap

func NewIntTreeMap[V any](options ...Option) *Map[int, V]

NewIntTreeMap 创建使用int键的TreeMap

func NewLinkedHashMap

func NewLinkedHashMap[K cmp.Ordered, V any](options ...Option) *Map[K, V]

NewLinkedHashMap 创建LinkedHashMap类型的并发映射

func NewStringHashMap

func NewStringHashMap[V any](options ...Option) *Map[string, V]

NewStringHashMap 创建使用string键的HashMap

func NewStringLinkedHashMap

func NewStringLinkedHashMap[V any](options ...Option) *Map[string, V]

NewStringLinkedHashMap 创建使用string键的LinkedHashMap

func NewStringTreeMap

func NewStringTreeMap[V any](options ...Option) *Map[string, V]

NewStringTreeMap 创建使用string键的TreeMap

func NewTreeMap

func NewTreeMap[K cmp.Ordered, V any](options ...Option) *Map[K, V]

NewTreeMap 创建TreeMap类型的并发映射

func (*Map[K, V]) Clear

func (m *Map[K, V]) Clear()

Clear 清空映射

func (*Map[K, V]) Empty

func (m *Map[K, V]) Empty() bool

Empty 检查是否为空

func (*Map[K, V]) Get

func (m *Map[K, V]) Get(key K) (value V, found bool)

Get 获取值

func (*Map[K, V]) GetMultiple

func (m *Map[K, V]) GetMultiple(keys []K) map[K]V

GetMultiple 批量获取

func (*Map[K, V]) IsDirty

func (m *Map[K, V]) IsDirty() (dirty bool)

IsDirty 检查映射是否被修改过

func (*Map[K, V]) Keys

func (m *Map[K, V]) Keys() []K

Keys 获取所有键

func (*Map[K, V]) LoadFromFile

func (m *Map[K, V]) LoadFromFile(filename string) error

LoadFromFile 从文件加载

func (*Map[K, V]) MarshalJSON

func (m *Map[K, V]) MarshalJSON() ([]byte, error)

MarshalJSON JSON序列化

func (*Map[K, V]) MarshalWith

func (m *Map[K, V]) MarshalWith(serializer *SerializerFunc) ([]byte, error)

MarshalWith 使用指定序列化器进行序列化

func (*Map[K, V]) Put

func (m *Map[K, V]) Put(key K, value V)

Put 插入键值对

func (*Map[K, V]) PutAll

func (m *Map[K, V]) PutAll(data map[K]V)

PutAll 批量插入

func (*Map[K, V]) Remove

func (m *Map[K, V]) Remove(key K)

Remove 删除键

func (*Map[K, V]) RemoveMultiple

func (m *Map[K, V]) RemoveMultiple(keys []K)

RemoveMultiple 批量删除

func (*Map[K, V]) SaveToFile

func (m *Map[K, V]) SaveToFile(filename string) (err error)

SaveToFile 保存到文件

func (*Map[K, V]) Size

func (m *Map[K, V]) Size() int

Size 获取大小

func (*Map[K, V]) String

func (m *Map[K, V]) String() string

String 字符串表示

func (*Map[K, V]) UnmarshalJSON

func (m *Map[K, V]) UnmarshalJSON(data []byte) error

UnmarshalJSON JSON反序列化

func (*Map[K, V]) UnmarshalWith

func (m *Map[K, V]) UnmarshalWith(data []byte, serializer *SerializerFunc) error

UnmarshalWith 使用指定序列化器进行反序列化

func (*Map[K, V]) Values

func (m *Map[K, V]) Values() []V

Values 获取所有值

type Option

type Option func(*Options)

Option 配置选项函数

func WithSerializer

func WithSerializer(v *SerializerFunc) Option

WithSerializer 设置序列化格式

func WithShardCount

func WithShardCount(count uint32) Option

WithShardCount 设置分片数量

type Options

type Options struct {
	ShardCount uint32
	Serializer *SerializerFunc
}

Options 创建Map的配置选项

type SerializableData

type SerializableData[K cmp.Ordered, V any] struct {
	Items []Tuple[K, V] `json:"items"`
}

SerializableData 可序列化的数据结构

type SerializerFunc

type SerializerFunc struct {
	NameFunc      func() string
	MarshalFunc   func(v interface{}) ([]byte, error)
	UnmarshalFunc func(data []byte, v interface{}) error
	// contains filtered or unexported fields
}

func GobSerializer

func GobSerializer() *SerializerFunc

func JsonSerializer

func JsonSerializer() *SerializerFunc

func JsoniterSerializer

func JsoniterSerializer() *SerializerFunc

func SonicSerializer

func SonicSerializer() *SerializerFunc

func (*SerializerFunc) IsJSON

func (s *SerializerFunc) IsJSON() bool

IsJSON 实现JSONCompatible接口

func (*SerializerFunc) Marshal

func (s *SerializerFunc) Marshal(v interface{}) ([]byte, error)

func (*SerializerFunc) Name

func (s *SerializerFunc) Name() string

func (*SerializerFunc) Unmarshal

func (s *SerializerFunc) Unmarshal(data []byte, v interface{}) error

type Tuple

type Tuple[K cmp.Ordered, V any] struct {
	Key   K `json:"key"`
	Value V `json:"value"`
}

Tuple 用于序列化的键值对

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL