From f55b3bc6092f8efa9516af1fb5bd7412beeffc75 Mon Sep 17 00:00:00 2001 From: ayflying Date: Thu, 27 Mar 2025 11:20:07 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E7=BC=93=E5=AD=98=E6=A8=A1?= =?UTF-8?q?=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 90 ++++++++++----- aycache/aycache.go | 11 +- drivers/db/elasticsearch/elasticsearch.go | 2 +- internal/logic/gameAct/gameAct.go | 19 ++++ pkg/aycache/cache.go | 2 +- pkg/aycache/drive/elasticsearch.go | 103 ++++++++++++++--- pkg/aycache/drive/file.go | 11 -- pkg/aycache/drive/redis.go | 1 - pkg/elasticsearch/elasticsearch.go | 128 +++++++++++----------- pkg/pkg.go | 5 + service/game_act.go | 1 + 11 files changed, 246 insertions(+), 127 deletions(-) diff --git a/README.md b/README.md index df7e82e..0e06c0b 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # utility_go:强大的Go语言工具类库 ## 一、项目概述 -`utility_go` 是一个功能丰富的Go语言工具类库,旨在帮助开发者更高效地开发Go应用程序。它提供了一系列实用的功能模块,涵盖了数据库操作、缓存处理、支付接口集成、排名算法实现等多个方面,可广泛应用于各种类型的Go项目中。 +`utility_go` 是一个功能丰富的Go语言工具类库,旨在助力开发者更高效地开发Go应用程序。它提供了一系列实用的功能模块,广泛涵盖数据库操作、缓存处理、支付接口集成、排名算法实现等多个方面,适用于各类Go项目。 ## 二、安装方式 -要使用 `utility_go` 工具类库,你可以使用 `go get` 命令进行安装。请确保你的Go环境已经正确配置,并且可以访问互联网。 +要使用 `utility_go` 工具类库,可使用 `go get` 命令进行安装。请确保你的Go环境已正确配置,且可访问互联网。 ### 安装命令 ```sh @@ -12,7 +12,7 @@ go get github.com/ayflying/utility_go ``` ### 安装验证 -安装完成后,你可以在你的Go代码中导入 `utility_go` 相关的包,检查是否能够正常使用。例如: +安装完成后,你可以在Go代码中导入 `utility_go` 相关的包,检查是否能够正常使用。示例如下: ```go package main @@ -29,39 +29,45 @@ func main() { ``` ## 三、项目结构 -`utility_go` 的项目结构设计清晰,各个模块分工明确,方便开发者使用和扩展。以下是项目的主要目录结构: +`utility_go` 的项目结构设计清晰,各模块分工明确,便于开发者使用和扩展。以下是项目的主要目录结构及说明: ### 主要目录说明 -- **`api/`**:存放与API相关的代码,包含不同模块的API接口定义,如 `admin`、`callback`、`system` 等。这些API接口用于处理各种外部请求,是项目与外部系统交互的重要入口。 -- **`service/`**:服务层代码,包含各种业务逻辑的实现,如 `game_act.go`、`ip_2_region.go` 等。服务层负责处理具体的业务需求,将数据处理和业务逻辑封装在独立的函数或方法中,提高代码的可维护性和复用性。 -- **`controller/`**:控制器层代码,主要用于处理HTTP请求和响应。控制器接收客户端的请求,调用相应的服务层方法进行处理,并将处理结果返回给客户端。 -- **`internal/`**:内部包,包含项目的核心业务逻辑,如 `game`、`logic`、`model` 等模块。其中,`model` 模块定义了项目中使用的数据模型,如数据库表对应的结构体;`logic` 模块实现了各种业务逻辑的处理函数。 -- **`package/`**:包含各种功能包,提供了丰富的工具和功能,具体如下: - - **`aycache`**:缓存相关的功能包,提供了缓存操作的接口和实现,帮助开发者更方便地使用缓存技术,提高应用程序的性能。 - - **`elasticsearch`**:Elasticsearch相关的功能包,用于与Elasticsearch搜索引擎进行交互,实现数据的存储、检索和分析等功能。 - - **`excel`**:Excel处理相关的功能包,提供了Excel文件的读写操作接口,方便开发者处理Excel文件中的数据。 - - **`pay`**:支付相关的功能包,包含了与各种支付平台的接口集成,如 `apple`(苹果支付)、`playstore`(Google Play Store支付)等,支持应用内购买等支付功能。 - - **`rand`**:随机数相关的功能包,提供了生成各种随机数的函数,可用于测试、加密等场景。 - - **`rank`**:排名相关的功能包,实现了各种排名算法,如基于Redis的排行榜功能,可用于游戏排名、活动排名等场景。 - - **`s3`**:S3存储相关的功能包,用于与Amazon S3等云存储服务进行交互,实现文件的上传、下载、删除等操作。 -- **`tools/`**:工具类代码,包含了一些常用的工具函数,如 `redis.go`(Redis操作相关)、`time.go`(时间处理相关)、`tools.go`(通用工具函数)等,方便开发者在项目中使用。 +- **api/**:存放与API相关的代码,包含不同模块的API接口定义,如 `admin`、`callback`、`system` 等。这些API接口用于处理各种外部请求,是项目与外部系统交互的重要入口。 +- **service/**:服务层代码,包含各种业务逻辑的实现,如 `game_act.go`、`ip_2_region.go` 等。服务层负责处理具体的业务需求,将数据处理和业务逻辑封装在独立的函数或方法中,提高代码的可维护性和复用性。 +- **controller/**:控制器层代码,主要用于处理HTTP请求和响应。控制器接收客户端的请求,调用相应的服务层方法进行处理,并将处理结果返回给客户端。 +- **internal/**:内部包,包含项目的核心业务逻辑,如 `game`、`logic`、`model` 等模块。其中,`model` 模块定义了项目中使用的数据模型,如数据库表对应的结构体;`logic` 模块实现了各种业务逻辑的处理函数。 +- **package/**:包含各种功能包,提供了丰富的工具和功能,具体如下: + - **aycache**:缓存相关的功能包,提供了缓存操作的接口和实现,帮助开发者更方便地使用缓存技术,提高应用程序的性能。 + - **elasticsearch**:Elasticsearch相关的功能包,用于与Elasticsearch搜索引擎进行交互,实现数据的存储、检索和分析等功能。 + - **excel**:Excel处理相关的功能包,提供了Excel文件的读写操作接口,方便开发者处理Excel文件中的数据。 + - **pay**:支付相关的功能包,包含了与各种支付平台的接口集成,如 `apple`(苹果支付)、`playstore`(Google Play Store支付)等,支持应用内购买等支付功能。 + - **rand**:随机数相关的功能包,提供了生成各种随机数的函数,可用于测试、加密等场景。 + - **rank**:排名相关的功能包,实现了各种排名算法,如基于Redis的排行榜功能,可用于游戏排名、活动排名等场景。 + - **s3**:S3存储相关的功能包,用于与Amazon S3等云存储服务进行交互,实现文件的上传、下载、删除等操作。 +- **tools/**:工具类代码,包含了一些常用的工具函数,如 `redis.go`(Redis操作相关)、`time.go`(时间处理相关)、`tools.go`(通用工具函数)等,方便开发者在项目中使用。 ## 四、主要模块功能 -### 4.1 `pay/playstore` -该模块主要用于与Google Play Store API交互,处理应用内购买相关的操作。它提供了以下主要功能: -- **创建客户端**:通过 `New` 函数创建并返回一个包含访问androidpublisher API所需凭证的http客户端,方便开发者与Google Play Store API进行通信。 -- **使用自定义客户端**:`NewWithClient` 函数允许开发者使用自定义的http客户端创建并返回一个包含访问androidpublisher API所需凭证的http客户端,增加了客户端的灵活性。 +### 4.1 pay/playstore +该模块主要用于与Google Play Store API交互,处理应用内购买相关的操作,提供以下主要功能: +- **创建客户端**:通过 `New` 函数创建并返回一个包含访问 `androidpublisher` API所需凭证的HTTP客户端,方便开发者与Google Play Store API进行通信。 +- **使用自定义客户端**:`NewWithClient` 函数允许开发者使用自定义的HTTP客户端创建并返回一个包含访问 `androidpublisher` API所需凭证的HTTP客户端,增加了客户端的灵活性。 - **验证签名**:`VerifySignature` 函数用于验证应用内购买的签名,确保支付信息的安全性和合法性。 -### 4.2 `s3` -`s3` 模块主要用于与S3存储服务进行交互,提供了文件存储和管理的功能。其中,`ListBuckets` 函数可以列出S3存储桶的信息,方便开发者管理存储桶中的文件。 +### 4.2 s3 +`s3` 模块主要用于与S3存储服务进行交互,提供文件存储和管理的功能。其中,`ListBuckets` 函数可以列出S3存储桶的信息,方便开发者管理存储桶中的文件。 -### 4.3 `model` +### 4.3 model `model` 模块定义了项目中使用的数据模型,这些数据模型通常与数据库表相对应,用于数据的存储和操作。例如: -- **`GameMailMass`**:表示游戏邮件群发的数据模型,包含邮件的标题、内容、类型等信息。 -- **`GameBag`**:表示游戏背包的数据模型,包含用户标识、道具数据、图鉴、手势等信息。 -- **`MemberSave`**:(根据具体代码中的定义)可能表示用户会员信息的数据模型,用于存储用户的会员相关数据。 +- **GameMailMass**:表示游戏邮件群发的数据模型,包含邮件的标题、内容、类型等信息。 +- **GameBag**:表示游戏背包的数据模型,包含用户标识、道具数据、图鉴、手势等信息。 +- **MemberSave**:(根据具体代码中的定义)可能表示用户会员信息的数据模型,用于存储用户的会员相关数据。 + +### 4.4 tools +`tools` 模块提供了一系列通用工具函数,涵盖时间处理、Redis操作、道具数据处理等功能: +- **时间处理**:`time.go` 文件中的函数可以进行时间计算,如获取本周开始时间、计算两个时间间隔天数等。 +- **Redis操作**:`redis.go` 文件中的函数可以进行Redis的扫描操作,支持批量获取大量数据。 +- **通用工具**:`tools.go` 文件中的函数提供了字符串处理、切片操作、道具数据合并等功能。 ## 五、使用示例 @@ -115,6 +121,33 @@ func main() { } ``` +### 5.3 工具模块示例 +以下是一个使用 `tools` 模块处理道具数据的示例代码: +```go +package main + +import ( + "fmt" + "github.com/ayflying/utility_go/tools" +) + +func main() { + // 字符串转道具类型 + str := "1|10|2|20" + result := tools.Tools.Spilt2Item(str) + fmt.Println("Spilt2Item result:", result) + + // 切片换道具类型 + slice := []int64{1, 10, 2, 20} + res := tools.Tools.Slice2Item(slice) + fmt.Println("Slice2Item result:", res) + + // 道具格式转map + list := tools.Tools.Items2Map(result) + fmt.Println("Items2Map result:", list) +} +``` + ## 六、注意事项 - **自动生成文件**:项目中有部分代码文件是由GoFrame CLI工具生成并维护的,这些文件通常会标注有 `// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.` 注释。请不要手动修改这些文件,以免造成不必要的问题。 - **版本兼容性**:在使用 `utility_go` 工具类库时,请确保你的Go语言版本与工具类库的要求版本兼容。建议使用最新的Go语言版本,以获得更好的性能和稳定性。 @@ -123,5 +156,4 @@ func main() { `utility_go` 工具类库会定期进行更新和维护,以修复已知的问题、添加新的功能和优化性能。你可以关注项目的GitHub仓库(https://github.com/ayflying/utility_go)获取最新的更新信息。如果你在使用过程中遇到任何问题或有任何建议,欢迎提交Issue或Pull Request。 ## 八、许可证信息 -`utility_go` 工具类库遵循 MIT许可证,你可以在项目的 `LICENSE` 文件中查看详细的许可证条款。请确保在使用该工具类库时遵守相关的许可证规定。 -``` +`utility_go` 工具类库遵循MIT许可证,你可以在项目的 `LICENSE` 文件中查看详细的许可证条款。请确保在使用该工具类库时遵守相关的许可证规定。 \ No newline at end of file diff --git a/aycache/aycache.go b/aycache/aycache.go index aa5512f..13d7878 100644 --- a/aycache/aycache.go +++ b/aycache/aycache.go @@ -2,7 +2,6 @@ package aycache import ( "github.com/ayflying/utility_go/pkg/aycache/drive" - drive2 "github.com/ayflying/utility_go/pkg/aycache/drive" "github.com/gogf/gf/v2/os/gcache" ) @@ -24,13 +23,13 @@ func New(_name ...string) gcache.Adapter { } switch name { case "cache": - cacheAdapterObj = drive2.NewAdapterMemory() + cacheAdapterObj = drive.NewAdapterMemory() case "redis": - cacheAdapterObj = drive2.NewAdapterRedis() + cacheAdapterObj = drive.NewAdapterRedis() case "file": - cacheAdapterObj = drive2.NewAdapterFile("runtime/cache") - case "es": - cacheAdapterObj = drive.NewAdapterElasticsearch([]string{"http://127.0.0.1:9200"}) + cacheAdapterObj = drive.NewAdapterFile("runtime/cache") + //case "es": + //cacheAdapterObj = drive.NewAdapterElasticsearch("http://127.0.0.1:9200"}) } //var client = gcache.New() diff --git a/drivers/db/elasticsearch/elasticsearch.go b/drivers/db/elasticsearch/elasticsearch.go index 27a8595..08034e8 100644 --- a/drivers/db/elasticsearch/elasticsearch.go +++ b/drivers/db/elasticsearch/elasticsearch.go @@ -46,7 +46,7 @@ type elastic struct { //} // //// getDocument 获取文档 -//func (d *Driver) GetDocument(name string, id string) (res json.RawMessage) { +//func (d *Driver) Get(name string, id string) (res json.RawMessage) { // resp, err := d.client.Get(name, id). // Do(context.Background()) // if err != nil { diff --git a/internal/logic/gameAct/gameAct.go b/internal/logic/gameAct/gameAct.go index 3a7c750..386fdb5 100644 --- a/internal/logic/gameAct/gameAct.go +++ b/internal/logic/gameAct/gameAct.go @@ -222,3 +222,22 @@ func (s *sGameAct) RefreshGetRedDotCache(uid int64) { g.Dump(err) } } + +func (s *sGameAct) Del(uid int64, actId int) { + if uid == 0 || actId == 0 { + g.Log().Error(ctx, "当前参数为空") + return + } + // 构造缓存键名 + keyCache := fmt.Sprintf("act:%v:%v", actId, uid) + + //删除活动缓存 + g.Redis().Del(ctx, keyCache) + + //删除当前活动储存 + g.Model(Name).Where(do.GameAct{ + Uid: uid, + ActId: actId, + }).Delete() + +} diff --git a/pkg/aycache/cache.go b/pkg/aycache/cache.go index fd6e40b..cd38c81 100644 --- a/pkg/aycache/cache.go +++ b/pkg/aycache/cache.go @@ -29,7 +29,7 @@ func New(_name ...string) gcache.Adapter { case "file": cacheAdapterObj = drive2.NewAdapterFile("runtime/cache") case "es": - cacheAdapterObj = drive.NewAdapterElasticsearch([]string{"http://127.0.0.1:9200"}) + cacheAdapterObj = drive.NewAdapterElasticsearch(_name[1]) } //var client = gcache.New() diff --git a/pkg/aycache/drive/elasticsearch.go b/pkg/aycache/drive/elasticsearch.go index 0c4f92f..d37c216 100644 --- a/pkg/aycache/drive/elasticsearch.go +++ b/pkg/aycache/drive/elasticsearch.go @@ -2,23 +2,51 @@ package drive import ( "context" + "fmt" + "github.com/elastic/go-elasticsearch/v8" "github.com/gogf/gf/v2/container/gvar" + "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gcache" + "github.com/gogf/gf/v2/os/gctx" + "github.com/gogf/gf/v2/util/gconv" "time" ) +var ( + adapterElasticsearchClient gcache.Adapter +) + type AdapterElasticsearch struct { - //FilePath string - Addresses []string + client *elasticsearch.TypedClient + name string } -func (a AdapterElasticsearch) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error { - //TODO implement me - panic("implement me") +func (a AdapterElasticsearch) Set(ctx context.Context, _key interface{}, value interface{}, duration time.Duration) (err error) { + key := gconv.String(_key) + data := gconv.Map(value) + if duration > 0 { + data["delete_time"] = time.Now().Add(duration) + } + _, err = a.client.Index(a.name).Id(key). + Document(data).Do(ctx) + if err != nil { + fmt.Printf("indexing document failed, err:%v\n", err) + return + } + return } func (a AdapterElasticsearch) SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error { - //TODO implement me + for k, v := range data { + save := gconv.Map(v) + if duration > 0 { + save["delete_time"] = time.Now().Add(duration) + } + key := gconv.String(k) + a.client.Index(a.name).Id(key). + Document(save).Do(ctx) + } + panic("implement me") } @@ -37,9 +65,17 @@ func (a AdapterElasticsearch) SetIfNotExistFuncLock(ctx context.Context, key int panic("implement me") } -func (a AdapterElasticsearch) Get(ctx context.Context, key interface{}) (*gvar.Var, error) { - //TODO implement me - panic("implement me") +func (a AdapterElasticsearch) Get(ctx context.Context, key interface{}) (res *gvar.Var, err error) { + _key := gconv.String(key) + resp, err := a.client.Get(a.name, _key). + Do(context.Background()) + if err != nil { + fmt.Printf("get document by id failed, err:%v\n", err) + return + } + fmt.Printf("fileds:%s\n", resp.Source_) + res = gvar.New(resp.Source_) + return } func (a AdapterElasticsearch) GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (result *gvar.Var, err error) { @@ -82,9 +118,26 @@ func (a AdapterElasticsearch) Values(ctx context.Context) (values []interface{}, panic("implement me") } -func (a AdapterElasticsearch) Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) { - //TODO implement me - panic("implement me") +func (a AdapterElasticsearch) Update(ctx context.Context, _key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) { + key := gconv.String(_key) + data := gconv.Map(value) + oldValue, err = a.Get(ctx, key) + if err != nil { + exist = false + } else { + for k, v := range oldValue.Map() { + if _, ok := data[k]; !ok { + data[k] = v + } + } + } + + _, err = a.client.Update(a.name, key). + Doc(data).Do(context.Background()) + if err != nil { + return + } + return } func (a AdapterElasticsearch) UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error) { @@ -98,8 +151,15 @@ func (a AdapterElasticsearch) GetExpire(ctx context.Context, key interface{}) (t } func (a AdapterElasticsearch) Remove(ctx context.Context, keys ...interface{}) (lastValue *gvar.Var, err error) { - //TODO implement me - panic("implement me") + //获取keys最后一个 + lastKey := keys[len(keys)-1] + lastValue, _ = a.Get(ctx, lastKey) + + for k := range keys { + key := gconv.String(k) + a.client.Delete(a.name, key).Do(ctx) + } + return } func (a AdapterElasticsearch) Clear(ctx context.Context) error { @@ -112,8 +172,17 @@ func (a AdapterElasticsearch) Close(ctx context.Context) error { panic("implement me") } -func NewAdapterElasticsearch(addresses []string) gcache.Adapter { - return &AdapterElasticsearch{ - Addresses: addresses, +func NewAdapterElasticsearch(name string) gcache.Adapter { + + if adapterElasticsearchClient == nil { + _cfg, _ := g.Cfg().Get(gctx.New(), "elasticsearch") + var cfg elasticsearch.Config + _cfg.Scan(&cfg) + es, _ := elasticsearch.NewTypedClient(cfg) + adapterElasticsearchClient = &AdapterElasticsearch{ + client: es, + name: name, + } } + return adapterElasticsearchClient } diff --git a/pkg/aycache/drive/file.go b/pkg/aycache/drive/file.go index 7eff432..0ee115a 100644 --- a/pkg/aycache/drive/file.go +++ b/pkg/aycache/drive/file.go @@ -16,17 +16,6 @@ type AdapterFile struct { } func (a AdapterFile) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error { - //defer a.handleLruKey(ctx, key) - //expireTime := a.getInternalExpire(duration) - //a.data.Set(key, memoryDataItem{ - // a: value, - // a: expireTime, - //}) - //c.eventList.PushBack(&adapterMemoryEvent{ - // k: key, - // e: expireTime, - //}) - arr := strings.Split(":", gconv.String(key)) fileName := path.Join(arr...) return gfile.PutBytes(fileName, gconv.Bytes(value)) diff --git a/pkg/aycache/drive/redis.go b/pkg/aycache/drive/redis.go index d331367..734805c 100644 --- a/pkg/aycache/drive/redis.go +++ b/pkg/aycache/drive/redis.go @@ -19,7 +19,6 @@ func NewAdapterRedis() gcache.Adapter { redisObj, _ := gredis.New(cfg) //adapterRedisClient = gcache.NewAdapterRedis(g.Redis("default")) adapterRedisClient = gcache.NewAdapterRedis(redisObj) - adapterRedisCache.SetAdapter(adapterRedisClient) } return adapterRedisCache diff --git a/pkg/elasticsearch/elasticsearch.go b/pkg/elasticsearch/elasticsearch.go index 4377cfe..a8687f2 100644 --- a/pkg/elasticsearch/elasticsearch.go +++ b/pkg/elasticsearch/elasticsearch.go @@ -5,96 +5,102 @@ import ( "encoding/json" "fmt" "github.com/elastic/go-elasticsearch/v8" + "github.com/elastic/go-elasticsearch/v8/typedapi/core/bulk" + "github.com/elastic/go-elasticsearch/v8/typedapi/core/delete" + "github.com/elastic/go-elasticsearch/v8/typedapi/core/search" + "github.com/elastic/go-elasticsearch/v8/typedapi/core/update" + "github.com/elastic/go-elasticsearch/v8/typedapi/types" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/os/gctx" ) var ( es *elasticsearch.TypedClient ) -type elastic struct { +type Elastic struct { client *elasticsearch.TypedClient + name string } -func New(name ...string) *elastic { - // ES 配置 - cfg := elasticsearch.Config{ - Addresses: []string{ - "http://ay.cname.com:9200", - }, - } +func NewV1(name string) *Elastic { + var cfg elasticsearch.Config + _cfg := g.Cfg().MustGetWithEnv(gctx.New(), "elasticsearch") + _cfg.Scan(&cfg) if es == nil { var err error es, err = elasticsearch.NewTypedClient(cfg) if err != nil { fmt.Printf("elasticsearch.NewTypedClient failed, err:%v\n", err) - return &elastic{} + return &Elastic{} } } - return &elastic{ + return &Elastic{ client: es, + name: name, } } -// createIndex 创建索引 -func (s *elastic) CreateIndex(name string) { - resp, err := s.client.Indices. - Create(name). - Do(context.Background()) - if err != nil { - fmt.Printf("create index failed, err:%v\n", err) - return - } - fmt.Printf("index:%#v\n", resp.Index) -} - -// indexDocument 索引文档 -func (s *elastic) IndexDocument(name string, key string, data interface{}) { +//// Create 创建索引 +//func (s *Elastic) Create(ctx context.Context) { +// resp, err := s.client.Indices. +// Create(s.name).Do(ctx) +// if err != nil { +// fmt.Printf("create index failed, err:%v\n", err) +// return +// } +// fmt.Printf("index:%#v\n", resp.Index) +//} +// Set 索引文档 +func (s *Elastic) Set(ctx context.Context, key string, data interface{}) (err error) { // 添加文档 - resp, err := s.client.Index(name). - Id(key). - Document(data). - Do(context.Background()) - if err != nil { - fmt.Printf("indexing document failed, err:%v\n", err) - return - } - fmt.Printf("result:%#v\n", resp.Result) -} - -// getDocument 获取文档 -func (s *elastic) GetDocument(name string, id string) (res json.RawMessage) { - resp, err := s.client.Get(name, id). - Do(context.Background()) - if err != nil { - fmt.Printf("get document by id failed, err:%v\n", err) - return - } - fmt.Printf("fileds:%s\n", resp.Source_) - res = resp.Source_ + _, err = s.client.Index(s.name).Id(key).Document(data).Do(ctx) return } -// updateDocument 更新文档 -func (s *elastic) UpdateDocument(name string, key string, data interface{}) { - - resp, err := s.client.Update(name, key). - Doc(data). // 使用结构体变量更新 - Do(context.Background()) - if err != nil { - fmt.Printf("update document failed, err:%v\n", err) - return +// SetBulk 批量添加文档 +func (s *Elastic) SetBulk(ctx context.Context, data []any) (err error) { + var save *bulk.Request + save = &bulk.Request{ + data, } - fmt.Printf("result:%v\n", resp.Result) + s.client.Bulk().Index(s.name).Request(save).Do(ctx) + return } -// deleteDocument 删除 document -func (s *elastic) DeleteDocument(name string, key string) { - resp, err := s.client.Delete(name, key). - Do(context.Background()) +// Get 获取文档 +func (s *Elastic) Get(ctx context.Context, id string) (res json.RawMessage, err error) { + get, err := s.client.Get(s.name, id).Do(ctx) if err != nil { - fmt.Printf("delete document failed, err:%v\n", err) return } - fmt.Printf("result:%v\n", resp.Result) + res = get.Source_ + return +} + +// Update 更新文档 +func (s *Elastic) Update(ctx context.Context, key string, data interface{}) (res *update.Response, err error) { + res, err = s.client.Update(s.name, key).Doc(data).Do(ctx) + return +} + +// Delete 删除 document +func (s *Elastic) Delete(ctx context.Context, key string) (res *delete.Response, err error) { + res, err = s.client.Delete(s.name, key).Do(ctx) + if err != nil { + return + } + return +} + +// Select 查询 +func (s *Elastic) Select(ctx context.Context, query *types.MatchAllQuery) (res *search.Response, err error) { + res, err = s.client.Search(). //Index("my_index"). + Request(&search.Request{ + Query: &types.Query{ + MatchAll: &types.MatchAllQuery{}, + }, + }).Do(ctx) + return } diff --git a/pkg/pkg.go b/pkg/pkg.go index 224d25b..472e3e4 100644 --- a/pkg/pkg.go +++ b/pkg/pkg.go @@ -4,6 +4,7 @@ import ( v1 "github.com/ayflying/utility_go/api/pkg/v1" "github.com/ayflying/utility_go/pkg/aycache" "github.com/ayflying/utility_go/pkg/config" + "github.com/ayflying/utility_go/pkg/elasticsearch" "github.com/ayflying/utility_go/pkg/notice" "github.com/ayflying/utility_go/pkg/rank" "github.com/ayflying/utility_go/pkg/s3" @@ -38,3 +39,7 @@ func Websocket() *websocket.SocketV1 { func Config() *config.Cfg { return config.NewV1() } + +func Elastic(name string) *elasticsearch.Elastic { + return elasticsearch.NewV1(name) +} diff --git a/service/game_act.go b/service/game_act.go index 242a761..91049f1 100644 --- a/service/game_act.go +++ b/service/game_act.go @@ -33,6 +33,7 @@ type ( Save(actId int) (err error) // 清空GetRedDot缓存 RefreshGetRedDotCache(uid int64) + Del(uid int64, actId int) } )