cherry

package module
v1.5.3 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2026 License: MIT Imports: 14 Imported by: 28

README

🍒 欢迎使用 cherry!

cherry logo cherry license go version cherry tag

🌐 English Documentation

  • 高性能分布式的 Golang 游戏服务器框架
  • 采用 Golang + Actor Model 构建,具备高性能、可伸缩等特性
  • 简单易学,让开发者更专注于游戏业务开发

📦 安装

go get github.com/cherry-game/cherry

需要 Go 1.24+。

🚀 快速开始

package main

import (
    cherry "github.com/cherry-game/cherry"
)

func main() {
    app := cherry.Configure(
        "etc/profile/dev.json", // profile 路径
        "game-1",               // 节点 ID
        true,                   // 是否前端节点(接收客户端连接)
        cherry.Cluster,         // 集群模式
    )
    app.Startup()
}

🗺️ 架构

game-server-architecture

模块 路径 职责
应用装配 cherry.goapplication.go 组件注册、生命周期、启动
Actor 执行 net/actor/ 每 Actor 独立 goroutine,串行 mailbox,本地/远程/事件分发
集群通信 net/cluster/ + net/nats/ + net/discovery/ 跨节点 RPC,NATS 传输,成员发现
前端接入 net/parser/ + net/connector/ 协议解码,会话管理,agent Actor,WebSocket/TCP

🌟 核心功能

AppBuilder 与生命周期

通过 Builder API 将组件链式装配为运行中的服务:

cherry.Configure("etc/profile/dev.json", "game-1", true, cherry.Cluster).
    Register(myComponent).
    SetSerializer(cherryFacade.NewProtobuf()).
    AddActors(myActor).
    Startup()

生命周期保证:

Register → Set → Init → OnAfterInit → (运行中) → OnBeforeStop → OnStop

组件按注册的逆序停止。通过 SIGINT / SIGQUIT / SIGTERM 信号触发优雅关闭。

Actor 模型

每个 Actor 运行于独立 goroutine,逻辑串行处理。三种独立队列按 FIFO 原则消费:

队列 来源 用途
Local 客户端 → Actor 处理玩家请求
Remote Actor → Actor(跨节点) 服务间 RPC
Event 系统事件 解耦通知
type MyActor struct {
    capp.ActorLogger
}

func (p *MyActor) OnInit() {
    p.Local().Register("myHandler", p.handle)
    p.Remote().Register("myRemote", p.remote)
    p.EventRegister("eventName", p.onEvent)
}

func (p *MyActor) handle(session *cproto.Session, req *pb.MyReq) {
    p.Response(session, &pb.MyResp{Value: "ok"})
}

子 Actor — Actor 可创建子 Actor,消息由父 Actor 路由转发,子 Actor 与父 Actor 共享生命周期。

Actor Timer — 直接在 Actor 上注册定时器和定时任务,保证在 Actor 的 goroutine 上执行。

集群 & 注册发现

三种发现后端,通过 profile 配置切换:

模式 配置值 适用场景
default 从 profile 配置读取 单进程开发/测试
nats NATS 主从心跳发现 多节点生产环境
etcd etcd lease + watch 多节点生产环境(独立仓库)
discovery := app.Discovery()

// 成员查询
all := discovery.Map()
games := discovery.ListByType("game")
member, ok := discovery.Random("gate")

// Settings 同步(自动广播到所有节点)
discovery.UpdateSetting("region", "us-east")

// 成员变更回调
discovery.OnAddMember(func(m IMember) {
    // 新节点加入
})
discovery.OnRemoveMember(func(m IMember) {
    // 节点离开
})

基于 NATS 实现跨节点 RPC 调用,支持同步/异步方式,可配置超时时间。

连接器 & 协议

内置连接器:

  • TCP — 原生 Socket
  • WebSocket — 浏览器客户端
  • HTTP Server — REST API
  • HTTP Client — 对外请求

两种协议格式:

协议 格式 适用场景
Pomelo type(1b) + length(3b) + data 兼容 pomelo 各平台客户端
Simple id(4b) + dataLen(4b) + data 自定义轻量协议
消息 & 序列化

基于对象池的零分配消息传递:

msg := cherryFacade.GetMessage()
msg.Source = "game-1.player-100"
msg.Target = "map-1.aoi"
msg.FuncName = "enter"
msg.Args = myPayload
  • sync.Pool 消息池 + 引用计数,减少 GC 压力
  • 默认 Protobuf 序列化,同时支持 JSON
  • 同进程消息免序列化直传;跨节点消息通过 ClusterPacket 自动编解码
Extend 工具库

框架内置 21 个工具包:

分类
时间 time_wheel(分层时间轮),time(辅助函数、时间偏移、时间旅行)
ID 生成 snowflake(分布式唯一 ID),nuid
数据处理 compress(zlib),crypto(MD5、CRC32、Base64),gobjson
集合 mapslicequeuestring
基础设施 filehttp/clientnetsync(限流器)
反射 reflectmapstructureregex(带缓存)
编码 base58
// 时间轮 — 调度器、超时、延迟执行
tw := cherryTimeWheel.NewTimeWheel(time.Millisecond*10, 20)
tw.AfterFunc(time.Second, func() { /* ... */ })

// Snowflake 唯一 ID
node, _ := cherrySnowflake.NewNode(1)
id := node.Generate()
错误码

框架内置分层错误码:

if code.IsFail(errCode) {
    p.ResponseCode(session, errCode)
    return
}

预定义错误码:OK(0),会话错误(10+),RPC 错误(20+),Actor 错误(24+)。

日志

基于 uber-go/zap 封装:

  • 结构化日志,支持键值对输出
  • 多文件输出 + 日志切割
  • 可配置日志级别和堆栈跟踪级别
  • 控制台与文件可同时输出

🧰 扩展组件

已开放组件
组件 说明
data-config 策划配表读取管理,支持多种加载方式及数据查询
etcd 基于 etcd 的集群注册发现
gin 集成 gin 实现 HTTP server,支持中间件
gorm MySQL 数据库访问,支持多数据库配置
mongo MongoDB 访问,支持多数据库配置
cron 基于 robfig/cron 的定时任务

仓库地址:cherry-game/components

待开放组件

DB 写队列、gopher-lua 脚本、限流组件等

📖 示例

单节点精简版聊天室

适合新手熟悉项目,具备以下特性:

  • 基于网页客户端,构建 HTTP 服务器
  • 采用 WebSocket 作为连接器
  • 使用 JSON 作为通信格式
  • 实现创建房间、发送消息、广播消息等功能

源码位置:examples/demo_chat

多节点分布式游戏示例

适合作为基础框架构建游戏服务端,特性如下:

  • 基于 H5 构建客户端
  • 搭建 Web 服、网关服、中心服、游戏服等节点
  • 实现区服列表、多 SDK 帐号体系、帐号注册、登录、创建角色等功能

源码位置:examples/demo_cluster

准备步骤详见:环境安装与配置

🎮 游戏客户端 SDK

兼容 pomelo 协议的客户端均可接入 Cherry。

平台 客户端
Unity3D YMoonRiver/Pomelo_UnityWebSocketNetEase/pomelo-unityclient
Cocos2d-x NetEase/pomelo-cocos2dchat
JavaScript pomelonode/pomelo-jsclient-websocket
C topfreegames/libpitayaNetEase/libpomelo
iOS NetEase/pomelo-iosclient
Android / Java NetEase/pomelo-androidclient
微信 wangsijie/pomelo-weixin-client

协议格式:协议结构图pomelo wiki 协议格式

💬 讨论与交流

🙏 致谢

  • pomelo — 初代 Node.js 游戏服务端框架
  • pitaya — Go 游戏服务端框架

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AppBuilder added in v1.3.0

type AppBuilder struct {
	*Application
	// contains filtered or unexported fields
}

func Configure added in v1.1.5

func Configure(profileFilePath, nodeID string, isFrontend bool, mode NodeMode) *AppBuilder

func ConfigureNode added in v1.3.10

func ConfigureNode(node cfacade.INode, isFrontend bool, mode NodeMode) *AppBuilder

func (*AppBuilder) AddActors added in v1.3.0

func (p *AppBuilder) AddActors(actors ...cfacade.IActorHandler)

func (*AppBuilder) NetParser added in v1.3.0

func (p *AppBuilder) NetParser() cfacade.INetParser

func (*AppBuilder) Register added in v1.3.0

func (p *AppBuilder) Register(component ...cfacade.IComponent)

func (*AppBuilder) SetCluster added in v1.5.0

func (a *AppBuilder) SetCluster(cluster cfacade.IClusterComponent)

func (*AppBuilder) SetDiscovery added in v1.5.0

func (p *AppBuilder) SetDiscovery(discovery cfacade.IDiscoveryComponent)

func (*AppBuilder) SetNetParser added in v1.3.0

func (a *AppBuilder) SetNetParser(netParser cfacade.INetParser)

func (*AppBuilder) SetSerializer added in v1.5.0

func (p *AppBuilder) SetSerializer(serializer cfacade.ISerializer)

func (*AppBuilder) Startup added in v1.3.0

func (p *AppBuilder) Startup()

type Application

type Application struct {
	cfacade.INode
	// contains filtered or unexported fields
}

func NewApp

func NewApp(profileFilePath, nodeID string, isFrontend bool, mode NodeMode) *Application

NewApp create new application instance

func NewAppNode added in v1.3.10

func NewAppNode(node cfacade.INode, isFrontend bool, mode NodeMode) *Application

func (*Application) ActorSystem added in v1.3.0

func (a *Application) ActorSystem() cfacade.IActorSystem

func (*Application) All

func (a *Application) All() []cfacade.IComponent

func (*Application) Cluster added in v1.3.0

func (a *Application) Cluster() cfacade.ICluster

func (*Application) DieChan added in v1.1.22

func (a *Application) DieChan() chan bool

func (*Application) Discovery added in v1.3.0

func (a *Application) Discovery() cfacade.IDiscovery

func (*Application) Find

func (a *Application) Find(name string) cfacade.IComponent

func (*Application) IsFrontend added in v1.1.6

func (a *Application) IsFrontend() bool

func (*Application) NodeMode added in v1.1.6

func (a *Application) NodeMode() NodeMode

func (*Application) OnShutdown added in v1.1.0

func (a *Application) OnShutdown(fn ...func())

func (*Application) Register added in v1.1.5

func (a *Application) Register(components ...cfacade.IComponent)

func (*Application) Remove

func (a *Application) Remove(name string) cfacade.IComponent

Remove component by name

func (*Application) Running

func (a *Application) Running() bool

func (*Application) Serializer added in v1.3.0

func (a *Application) Serializer() cfacade.ISerializer

func (*Application) Shutdown

func (a *Application) Shutdown()

func (*Application) StartTime added in v1.1.0

func (a *Application) StartTime() string

func (*Application) Startup

func (a *Application) Startup()

Startup load components before startup

type NodeMode added in v1.1.6

type NodeMode byte
const (
	Cluster    NodeMode = 1 // 集群模式
	Standalone NodeMode = 2 // 单机模式
)

Directories

Path Synopsis
Package cherryCode defines the framework's numeric status codes and their helpers.
Package cherryCode defines the framework's numeric status codes and their helpers.
components
cron module
data-config module
etcd module
gin module
gops module
gorm module
mongo module
Package cherryConst holds framework-wide constants: version, logo, and separators.
Package cherryConst holds framework-wide constants: version, logo, and separators.
Package cherryError provides lightweight error constructors and sentinel errors used throughout the Cherry framework.
Package cherryError provides lightweight error constructors and sentinel errors used throughout the Cherry framework.
examples module
extend
base58
Package cherryBase58 file from https://github.com/akamensky/base58/blob/master/base58.go
Package cherryBase58 file from https://github.com/akamensky/base58/blob/master/base58.go
gob
map
Package cherryMap file from https://github.com/gogf/gf
Package cherryMap file from https://github.com/gogf/gf
mapstructure
Package cherryMapStructure exposes functionality to convert one arbitrary Go type into another, typically to convert a map[string]interface{} into a native Go structure.
Package cherryMapStructure exposes functionality to convert one arbitrary Go type into another, typically to convert a map[string]interface{} into a native Go structure.
net
queue
Package cherryQueue provides an efficient implementation of a multi-producer, single-consumer lock-free queue.
Package cherryQueue provides an efficient implementation of a multi-producer, single-consumer lock-free queue.
regex
Package cherryRegex file from https://github.com/gogf/gf
Package cherryRegex file from https://github.com/gogf/gf
slice
Package cherrySlice code from: https://github.com/beego/beego/blob/develop/core/utils/slice.go
Package cherrySlice code from: https://github.com/beego/beego/blob/develop/core/utils/slice.go
snowflake
Package cherrySnowflake code from: https://github.com/bwmarrin/snowflake snowflake provides a very simple Twitter snowflake generator and parser.
Package cherrySnowflake code from: https://github.com/bwmarrin/snowflake snowflake provides a very simple Twitter snowflake generator and parser.
sync
Package cherrySync cherrySync file from https://github.com/beego/beego/blob/develop/core/utils/safemap.go
Package cherrySync cherrySync file from https://github.com/beego/beego/blob/develop/core/utils/safemap.go
time
Package cherryTime code from: https://github.com/golang-module/carbon
Package cherryTime code from: https://github.com/golang-module/carbon
time_wheel
Package cherryTimeWheel file from https://github.com/RussellLuo/timingwheel
Package cherryTimeWheel file from https://github.com/RussellLuo/timingwheel
utils
Package cherryUtils file from https://github.com/gogf/gf
Package cherryUtils file from https://github.com/gogf/gf
Package cherryFacade defines the core interfaces for the Cherry framework.
Package cherryFacade defines the core interfaces for the Cherry framework.
rotatelogs
Package rotatelogs is a port of File-RotateLogs from Perl (https://metacpan.org/release/File-RotateLogs), and it allows you to automatically rotate output files when you write to them according to the filename pattern that you can specify.
Package rotatelogs is a port of File-RotateLogs from Perl (https://metacpan.org/release/File-RotateLogs), and it allows you to automatically rotate output files when you write to them according to the filename pattern that you can specify.
net
discovery
Package cherryDiscovery provides cluster node discovery for the Cherry framework.
Package cherryDiscovery provides cluster node discovery for the Cherry framework.
Package cherryProfile provides profile configuration file loading and node config resolution for the Cherry framework.
Package cherryProfile provides profile configuration file loading and node config resolution for the Cherry framework.

Jump to

Keyboard shortcuts

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