{"id":13692423,"url":"https://github.com/jukylin/esim","last_synced_at":"2025-05-02T19:32:04.640Z","repository":{"id":57515796,"uuid":"233334505","full_name":"jukylin/esim","owner":"jukylin","description":"微服务应用框架","archived":false,"fork":false,"pushed_at":"2021-12-23T03:13:09.000Z","size":25519,"stargazers_count":100,"open_issues_count":5,"forks_count":23,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-11-12T18:40:37.018Z","etag":null,"topics":["cola","ddd","dependency-injection","distributed","microservice","mock"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jukylin.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-01-12T03:49:04.000Z","updated_at":"2024-10-14T15:05:17.000Z","dependencies_parsed_at":"2022-08-28T16:51:25.459Z","dependency_job_id":null,"html_url":"https://github.com/jukylin/esim","commit_stats":null,"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jukylin%2Fesim","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jukylin%2Fesim/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jukylin%2Fesim/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jukylin%2Fesim/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jukylin","download_url":"https://codeload.github.com/jukylin/esim/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252095338,"owners_count":21693899,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cola","ddd","dependency-injection","distributed","microservice","mock"],"created_at":"2024-08-02T17:00:57.777Z","updated_at":"2025-05-02T19:32:04.026Z","avatar_url":"https://github.com/jukylin.png","language":"Go","funding_links":[],"categories":["开源类库","Open source library"],"sub_categories":["DDD 框架","DDD Framework"],"readme":"# Esim文档\n\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;Esim专注解决业务问题：业务复杂度，如何测试，代码组织，扩展等问题。不会提供微服务整套技术体系，服务治理、服务注册、服务发现等都不是它专注解决的问题，这部分问题我们交给了Service Mesh。\n\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;做为业务框架，Esim默认集成了gin和grpc两个技术框架，但吸收了业务和技术分离思想，所以为集成其他技术框架提供了接口，只要实现[Transports](https://github.com/jukylin/esim/blob/master/transports/interface.go#L3)接口，再把实例注册到```App.trans```就可以很轻松的集成其他技术框架。\n\n```\ntype Transports interface {\n\t// start server\n\tStart()\n\n\t// graceful shutdown server\n\tGracefulShutDown()\n}\n\nfunc (app *App) RegisterTran(tran transports.Transports) {\n\tapp.trans = append(app.trans, tran)\n}\n\n```\n\n## 安装\n\n\u003e 环境 go 1.3 及以上\n\n\u003e 使用 module 包管理工具\n\n\u003e go get github.com/jukylin/esim\n\n\u003e cd github.com/jukylin/esim\n\n\u003e go build -o esim ./tool \u0026\u0026 mv ./esim $GOPATH/bin\n\n## 创建项目\n\n```golang\nesim new -s test\n```\n\n### 浏览器访问\n\n#### 启动服务\n```golang\ncd test\n\ngo run main.go\n```\n\n#### 访问\n\n\u003e http://localhost:8080\n\n\n### 使用组件测试 [推荐]\n\n```\ncd  test/internal/transports/http/component-test/\ngo test\n```\n\n## 架构\n\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;Esim的架构来源于《实现领域驱动设计》的六边形架构和阿里的COLA架构，这2个架构有一个共同点：业务与技术分离。这点很好的解决了由于微服务架构增加的网络通讯和事件导致开发效率越来越慢的问题。所以才决定由原来的三层架构转为四层架构。\n\n\n![此处输入图片的描述][1]\n\n## 分层\n\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;Esim使用松散的分层架构，上层可以任意调用下层。使用松散的分层架构的原因，是因为我们在使用四层架构的过程中发现：一些简单的场景，app层的service只是增加了一层调用，并没有起到协调的作用，反而增加了一些不必要的工作，所以使用松散的架构，让controller直接调用domain的逻辑。\n\n\u003e **不能因为使用松散的架构，把原有app层的service职责都放到了controller里面！！！**\n\n![此处输入图片的描述][2]\n\n### 各层职责\n\n目录 | 职责\n---|---\ncontroller | 负责显示信息和解析、校验请求，适配不同终端\napplication | 不包含业务规则，为下一层领域模型协调任务，分配工作\ndomain| 负责表达业务概念，业务状态信息和业务规则，是业务软件的核心\ninfrastructure|为各层提供技术支持，持久化，领域事件等\n\n### 编码规范\n\n- [Uber Style 编码规范](https://github.com/xxjwxc/uber_go_guide_cn)\n\n- 函数第一个参数是ctx！函数第一个参数是ctx！函数第一个参数是ctx！\n\n- 禁止在defer内做逻辑运算\n\n- 业务代码形参、实参、返回值的类型不允许使用interface\n\n- 命名\n\n\u0026emsp; | Jaeger\n---|---\n目录名 |小写/中横线\n函数名 |驼峰\n文件名 |下划线\n变量 | 驼峰\n常量 | 驼峰\n包名 | 当前目录名\n请求地址 | *小写\n请求参数 | 小驼峰\n返回参数 | 小驼峰\n\n\n### v1 目录 + 文件名\n\n目录 | 定义 | 文件 | 类 | 接口\n---|---|---|---|---\napplication/service |应用层|index_service.go | IndexService|无\ndomain/service|领域服务 | index_service.go | IndexService|无\ndomain/entity |实体| index_entity.go | IndexEntity|无\ninfra/event |领域事件|index_event.go | PubIndexEvent | IndexEvent\ninfra/repo|资源库|index_repo.go| DBIndexRepo |IndexRepo\ninfra/dao|数据访问对象| index_dao.go| IndexDao |无\n\n### v2 目录\n\n目录 | 定义 | 文件 | 类 | 接口\n---|---|---|---|---\napplication/service |应用层|index.go | IndexService|无\ndomain/service|领域服务 | index.go | IndexService|无\ndomain/entity |实体| index.go | IndexEntity|无\ninfra/event |领域事件|index.go | PubIndexEvent | IndexEvent\ninfra/repo|资源库|index.go| DBIndexRepo |IndexRepo\ninfra/dao|数据访问对象| index.go| IndexDao |无\n\n\n\n### 数据库设计规范小三样\n\n```mysql\n`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\n`last_update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',\n`is_deleted` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0' COMMENT '删除标识',\n```\n\n\n## 特性\n\n- 由三层架构演进为四层架构（DDD + COLA）\n- 面向接口编程\n- 编译时的依赖注入\n- 管控业务使用的网络io\n- 融入log，opentracing，metrice提升服务可观察性\n- 单元测试友好，面向TDD\n\n\n## 依赖注入\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;Esim 使用[wire](https://github.com/google/wire)实现编译时的依赖注入，它有以下优点：\n\n- 当依赖关系图变得复杂时，运行时依赖注入很难跟踪和调试。 使用代码生成意味着在运行时执行的初始化代码是常规的，惯用的Go代码，易于理解和调试。不会因为框架的各种奇技淫巧而变得生涩难懂。特别重要的是，忘记依赖项等问题会成为编译时错误，而不是运行时错误。\n- 与服务定位器不同，不需要费心编造名称来注册服务。 Wire使用Go语法中的类型将组件与其依赖项连接起来。\n- 更容易防止依赖项变得臃肿。Wire生成的代码只会导入您需要的依赖项，因此您的二进制文件将不会有未使用的导入。 运行时依赖注入在运行之前无法识别未使用的依赖项。\n- Wire的依赖图是静态可知的，这为工具化和可视化提供了可能。\n\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;Esim将wire用于业务与基础设施之间。将基础设施的初始化从业务抽离出来，集中管理。\n\n### Esim使用wire示例\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;基础设施的依赖和初始化都在 ```infra/infra.go``` 文件下。wire的使用主要分2步，以增加mysqlClient为例：\n\n#### provide\n##### before\n\n```golang\ntype Infra struct {\n\t*container.Esim\n}\n\nvar infraSet = wire.NewSet(\n\twire.Struct(new(Infra), \"*\"),\n\tprovideEsim,\n)\n```\n\n##### after\n\n```golang\n\ntype Infra struct {\n\t*container.Esim\n\n\tDB mysql.MysqlClient\n}\n\nvar infraSet = wire.NewSet(\n\twire.Struct(new(Infra), \"*\"),\n\tprovideEsim,\n\tprovideDb,\n)\n\nfunc provideDb(esim *container.Esim) mysql.MysqlClient {\n    ......\n\treturn mysqlClent\n}\n```\n\n#### Inject\n\n\u003e 在当前目录下执行：```wire```命令，看到：\n\n```linux\nwire: projectPath/internal/infra: wrote projectPath/internal/infra/wire_gen.go\n```\n\u003e 说明执行成功，就可以在项目中使用了。\n\n```golang\ninfra.NewInfra().DB\n```\n\n## 依赖倒置\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;依赖倒置和依赖注入一样，主要应用于业务与基础设施之间。主要的作用是让业务与技术实现分离。在实际的使用中我们把涉及io操作都放到了基础设施的资源库上。这样做的好处：\n\n- 单元测试变简单，使用mock代替数据源\n- 不用学习各种 mock sdk，只针对 app 和 domain写单元测试\n- 不依赖远程，可以单机进行开发\n\n## 工具\n\n- esim db2entity -d db_name -t table_name\n\n\u003e 前置条件：\n\u003e 1. 在项目根目录下\n\u003e 2. 配置环境变量\n\n```linux\nexport ESIM_DB_HOST=127.0.0.1\nexport ESIM_DB_PORT=3306\nexport ESIM_DB_USER=root\nexport ESIM_DB_PASSWORD=123456\n```\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;由于DDD开发方式多了很多目录、文件，导致这部分工作变得很繁琐，所以```db2entity``` 从mysql数据库的表开始，自动建立实体，生成简单的CRUD语句和资源库的接口与实现，并把生成的资源库注入到基础设施。一气呵成。\n\n- esim factory --sname struct_name -n\n\n\u003e 前置条件:\n\u003e 1. 在模型目录下\n\u003e 2. 开启 module， ```export GO111MODULE=on```\n\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;```factory``` 命令可以自动对结构体进行初始化，内存对齐，生成临时对象池，reset和释放资源等操作，减少一些繁杂操作。\n\n- esim ifacer --iname 接口名称\n\n\u003e 前置条件:\n\u003e 1. 在接口目录下\n\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;```ifacer``` 命令根据接口的定义生成空实例\n\n- esim test\n\n![esim test](https://s1.ax1x.com/2020/06/06/tc9qS0.gif)\n\n\u003e 前置条件:\n\u003e 1. 项目目录下\n\u003e 2. 推荐使用[gotests](https://github.com/cweill/gotests)\n\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;```test``` 命令监听项目被修改文件，并在文件目录下执行```go test``` 自动运行单元测试。当然为了减轻一些繁杂的工作，```esim test```还会执行[wire](https://github.com/google/wire), [mockery](https://github.com/vektra/mockery)等命令\n\n\n## 配置\n\n- 环境设置\n\n\u003e esim 默认为 dev 环境，esim主要由 dev 和 pro 环境\n\n\u003e export ENV=pro\n\n- 配置文件\n\n\u003e 配置文件在项目的conf目录下\n\n\u003e conf/conf.yaml\n\n- provide\n\n```golang\nfunc provideConf(){\n    options := config.ViperConfOptions{}\n\n    file := []string{\"conf/monitoring.yaml\", \"conf/conf.yaml\"}\n    conf := config.NewViperConfig(options.WithConfigType(\"yaml\"),\n    \toptions.WithConfFile(file))\n\n    return conf\n}\n```\n\n- reference\n\n```golang\nservice_name := infra.NewInfra().Conf.GetString(\"appname\")\n```\n\n## 日志\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;日志会根据不同环境打印日志，开发和测试环境会把所有日志打印到终端，生产只会打印warn及以上的日志。\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;2套日志接口，一套没有上下文，一套有。使用上下文是为了把分布式环境下的日志通过tracer_id串起来。\n\n- provide\n\n```golang\nfunc provideLogger(conf config.Config) log.Logger {\n\tvar loggerOptions log.LoggerOptions\n\n\tlogger := log.NewLogger(\n\t\tloggerOptions.WithDebug(conf.GetBool(\"debug\")),\n\t)\n\treturn logger}\n```\n\n- reference\n\n```golang\ninfra.NewInfra().Logger.Infof(\"info %s\", \"test\")\n\ninfra.NewInfra().Logger.Infoc(ctx, \"info %s\", \"test\")\n```\n\n\n\n## HTTP\n\u003e 比官方接口多了（ctx）参数\n\n- provide\n\n```golang\nfunc provideHttp(esim *container.Esim) *http.HttpClient {\n\tclientOptions := http.ClientOptions{}\n\thttpClent := http.NewHttpClient(\n\t\tclientOptions.WithTimeOut(esim.Conf.GetDuration(\"http_client_time_out\")),\n        clientOptions.WithProxy(\n            func() interface {} {\n                monitorProxyOptions := http.MonitorProxyOptions{}\n                return http.NewMonitorProxy(\n                    monitorProxyOptions.WithConf(esim.Conf),\n                    monitorProxyOptions.WithLogger(esim.Logger))\n            }),\n\t)\n\n\treturn httpClent\n}\n```\n\n- reference\n\n```golang\nresp, err := infra.NewInfra().Http.GetCtx(ctx, \"http://www.baidu.com\")\ndefer resp.Body.Close()\n\n```\n\n\n## Mongodb\n\u003e 文档 https://github.com/mongodb/mongo-go-driver\n\n- provide\n\n```golang\nfunc provideMongodb(esim *container.Esim) mongodb.MgoClient {\n\toptions := mongodb.MgoClientOptions{}\n\tmongo := mongodb.NewMongo(\n\t\tmgoClientOptions.WithLogger(esim.logger),\n\t\tmgoClientOptions.WithConf(esim.conf),\n\t\tmgoClientOptions.WithMonitorEvent(\n\t\t\tfunc() MonitorEvent {\n\t\t\t\tmonitorEventOptions := MonitorEventOptions{}\n\t\t\t\treturn NewMonitorEvent(\n\t\t\t\t\tmonitorEventOptions.WithConf(esim.conf),\n\t\t\t\t\tmonitorEventOptions.WithLogger(esim.logger),\n\t\t\t\t)\n\t\t\t},\n\t\t)\n\t)\n\n\treturn mongo\n}\n```\n\n- reference\n\n```golang\n\nimport \"go.mongodb.org/mongo-driver/bson\"\n\ntype Info struct{\n\tTitle string\n}\n\n\ninfo := Info{}\n\ncoll := infra.NewInfra().Mgo.GetColl(\"database\", \"coll\")\nfilter := bson.M{\"phone\": \"123456\"}\nres := coll.FindOne(inf.Mgo.GetCtx(c.Request.Context()), filter).Decode(\u0026info)\n\n```\n\n## GRPC\n\u003e 文档 https://github.com/grpc/grpc-go\n\n- provide\n\n```golang\nfunc provideGrpcClient(esim *container.Esim) *grpc.GrpcClient {\n\n\tclientOptional := grpc.ClientOptionals{}\n\tclientOptions := grpc.NewClientOptions(\n\t\tclientOptional.WithLogger(esim.Logger),\n\t\tclientOptional.WithConf(esim.Conf),\n\t)\n\n\tgrpcClient := grpc.NewClient(clientOptions)\n\n\treturn grpcClient\n}\n```\n\n- reference\n\n```golang\nimport (\n    \"pathto/protobuf/passport\"\n)\n\nconn := infra.NewInfra().GrpcClient.DialContext(ctx, \":60080\")\ndefer conn.Close()\n\nclient := passport.NewUserInfoClient(conn)\n\ngetUserByUserNameRequest := \u0026passport.GetUserByUserNameRequest{}\ngetUserByUserNameRequest.Username = \"123456\"\n\nreplyData, err = client.GetUserByUserName(ctx, getUserByUserNameRequest)\n```\n\n## Redis\n\u003e 文档 https://github.com/gomodule/redigo\n\n- provide\n\n```golang\nfunc provideRedis(esim *container.Esim) *redis.RedisClient {\n\tredisClientOptions := redis.RedisClientOptions{}\n\tredisClent := redis.NewRedisClient(\n\t\tredisClientOptions.WithConf(esim.Conf),\n\t\tredisClientOptions.WithLogger(esim.Logger),\n\t\tredisClientOptions.WithProxy(\n\t\t\tfunc() interface{} {\n\t\t\t\tmonitorProxyOptions := redis.MonitorProxyOptions{}\n\t\t\t\treturn redis.NewMonitorProxy(\n\t\t\t\t\tmonitorProxyOptions.WithConf(esim.Conf),\n\t\t\t\t\tmonitorProxyOptions.WithLogger(esim.Logger),\n\t\t\t\t\tmonitorProxyOptions.WithTracer(esim.Tracer),\n\t\t\t\t)\n\t\t\t},\n\t\t),\n\t)\n\n\treturn redisClent\n}\n```\n\n- reference\n\n```golang\n\nconn := infra.NewInfra().Redis.GetCtxRedisConn()\ndefer conn.Close()\nkey := \"username:\"+username\nexists, err := redis.Bool(conn.Do(ctx, \"exists\", key))\n```\n\n## Mysql\n\u003e 文档 https://gorm.io/docs/\n\n- provide\n\n```golang\nfunc provideDb(esim *container.Esim) *mysql.MysqlClient {\n    mysqlClientOptions := mysql.MysqlClientOptions{}\n\tmysqlClent := mysql.NewMysqlClient(\n\t\tmysqlClientOptions.WithConf(esim.Conf),\n\t\tmysqlClientOptions.WithLogger(esim.Logger),\n\t\tmysqlClientOptions.WithProxy(\n\t\t\tfunc() interface{} {\n\t\t\t\tmonitorProxyOptions := mysql.MonitorProxyOptions{}\n\t\t\t\treturn mysql.NewMonitorProxy(\n\t\t\t\t\tmonitorProxyOptions.WithLogger(esim.Logger),\n\t\t\t\t\tmonitorProxyOptions.WithConf(esim.Conf),\n\t\t\t\t\tmonitorProxyOptions.WithTracer(esim.Tracer),\n\t\t\t\t)\n\t\t\t},\n\t\t),\n\t)\n\n\treturn mysqlClent\n}\n```\n\n- reference\n\n```golang\nvar user model.User\ninfra.NewInfra().DB.GetDb(ctx, \"db\").Table(\"table\").Where(\"username = ?\", username).\n\tSelect([]string{\"id\"}).First(\u0026user)\n```\n\n## Opentracing\n\u003e \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp; Esim使用[Jaeger](https://www.jaegertracing.io/)实现分布式追踪，默认为关闭状态。开启需要使用jaeger-client-go自带的[环境变量](https://github.com/jaegertracing/jaeger-client-go#environment-variables)\n\n\n  [1]: https://imgconvert.csdnimg.cn/aHR0cHM6Ly9hdGEyLWltZy5jbi1oYW5nemhvdS5vc3MtcHViLmFsaXl1bi1pbmMuY29tL2EzM2I4MGJjYWM1ZWM3M2QwZDEzNThkNmI0OWExMTljLnBuZw?x-oss-process=image/format,png\n  [2]: https://upload.cc/i1/2019/12/26/86caKj.png\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjukylin%2Fesim","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjukylin%2Fesim","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjukylin%2Fesim/lists"}