Compare commits

..

2 Commits

Author SHA1 Message Date
ayflying
5b1f4066f3 工具类加入 2025-01-09 14:31:33 +08:00
ayflying
037541abc8 修改阿波罗的接入方式 2024-12-27 11:20:42 +08:00
9 changed files with 585 additions and 54 deletions

View File

@@ -3,21 +3,21 @@ package config
import (
"fmt"
"github.com/apolloconfig/agollo/v4"
"github.com/apolloconfig/agollo/v4/env/config"
apolloConfig "github.com/apolloconfig/agollo/v4/env/config"
"github.com/apolloconfig/agollo/v4/storage"
"github.com/gogf/gf/contrib/config/apollo/v2"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gres"
"github.com/gogf/gf/v2/text/gstr"
"path"
"sync"
"time"
)
var (
ApolloCfg *config.AppConfig
//ApolloCfg *apolloConfig.AppConfig
ApolloCfg *apollo.Config
ApolloListener []string
Item2Obj = map[string]Load{}
)
@@ -71,57 +71,97 @@ func (c *Cfg) GetUrlFile(name string) (jsonObj *gjson.Json, err error) {
}
// 获取阿波罗
//func (c *Cfg) GetApollo(name string, obj Load) (jsonObj *gjson.Json, err error) {
// jsonObj, err = c.GetApolloV2(name, obj)
// return
//
// //c.Lock.Lock()
// //defer c.Lock.Unlock()
// //
// //Item2Obj[name+".json"] = obj
// //var cfg = apolloConfig.AppConfig{
// // AppID: ApolloCfg.AppID,
// // Cluster: ApolloCfg.Cluster,
// // IP: ApolloCfg.IP,
// // NamespaceName: name + ".json",
// // Secret: ApolloCfg.Secret,
// // IsBackupConfig: ApolloCfg.IsBackupConfig,
// // BackupConfigPath: ApolloCfg.BackupConfigPath,
// // SyncServerTimeout: 60,
// // MustStart: true,
// //}
// ////cfg.NamespaceName = name + ".json"
// //
// //client, err := agollo.StartWithConfig(func() (*apolloConfig.AppConfig, error) {
// // return ApolloCfg, nil
// //})
// //if client == nil {
// // return
// //}
// //var getStr string
// //var getApollo *storage.Config
// //for range 5 {
// // getApollo = client.GetConfig(cfg.NamespaceName)
// // if getApollo != nil {
// // break
// // }
// // time.Sleep(time.Second * 5)
// //}
// //
// //if getApollo != nil {
// // getStr = getApollo.GetValue("content")
// // if getStr != "" {
// // //写入配置
// // gfile.PutContents(path.Join("manifest", "game", name+".json"), getStr)
// // }
// //} else {
// // jsonObj, err = c.GetFile(name)
// //}
// //jsonObj, err = gjson.DecodeToJson(getStr)
// ////首次运行加入监听器
// //if !gstr.InArray(ApolloListener, name) {
// // c2 := &CustomChangeListener{}
// // client.AddChangeListener(c2)
// // ApolloListener = append(ApolloListener, name)
// //}
// //return
//}
func (c *Cfg) GetApollo(name string, obj Load) (jsonObj *gjson.Json, err error) {
c.Lock.Lock()
defer c.Lock.Unlock()
Item2Obj[name+".json"] = obj
var cfg = config.AppConfig{
AppID: ApolloCfg.AppID,
Cluster: ApolloCfg.Cluster,
IP: ApolloCfg.IP,
NamespaceName: name + ".json",
Secret: ApolloCfg.Secret,
IsBackupConfig: ApolloCfg.IsBackupConfig,
BackupConfigPath: ApolloCfg.BackupConfigPath,
SyncServerTimeout: 60,
MustStart: true,
}
//cfg.NamespaceName = name + ".json"
client, err := agollo.StartWithConfig(func() (*config.AppConfig, error) {
return ApolloCfg, nil
})
if client == nil {
return
}
var getStr string
var getApollo *storage.Config
for range 10 {
getApollo = client.GetConfig(cfg.NamespaceName)
if getApollo != nil {
break
}
time.Sleep(time.Second * 5)
// 接入阿波罗配置
ApolloCfg.NamespaceName = name + ".json"
adapter, err := apollo.New(nil, *ApolloCfg)
if err != nil {
g.Log().Fatalf(nil, `%+v`, err)
}
// Change the adapter of default configuration instance.
g.Cfg(name).SetAdapter(adapter)
if getApollo != nil {
getStr = getApollo.GetValue("content")
if getStr != "" {
//写入配置
gfile.PutContents(path.Join("manifest", "game", name+".json"), getStr)
}
} else {
jsonObj, err = c.GetFile(name)
}
jsonObj, err = gjson.DecodeToJson(getStr)
//首次运行加入监听器
if !gstr.InArray(ApolloListener, name) {
//放置监听器
client, _ := agollo.StartWithConfig(func() (*apolloConfig.AppConfig, error) {
return &apolloConfig.AppConfig{
AppID: ApolloCfg.AppID,
Cluster: ApolloCfg.Cluster,
NamespaceName: ApolloCfg.NamespaceName,
IP: ApolloCfg.IP,
IsBackupConfig: ApolloCfg.IsBackupConfig,
BackupConfigPath: ApolloCfg.BackupConfigPath,
Secret: ApolloCfg.Secret,
SyncServerTimeout: ApolloCfg.SyncServerTimeout,
MustStart: ApolloCfg.MustStart,
}, nil
})
c2 := &CustomChangeListener{}
client.AddChangeListener(c2)
ApolloListener = append(ApolloListener, name)
ApolloListener = append(ApolloListener, name+".json")
}
cfg, err := g.Cfg(name).Get(nil, "content")
cfg.Scan(&jsonObj)
return
}
@@ -131,14 +171,6 @@ type CustomChangeListener struct {
}
func (c *CustomChangeListener) OnChange(changeEvent *storage.ChangeEvent) {
//write your code here
fmt.Println(changeEvent.Changes)
//for key, value := range changeEvent.Changes {
// fmt.Println("change key : ", key, ", value :", value)
//}
//fmt.Println(changeEvent.Namespace)
//c.wg.Done()
g.Log().Debugf(nil, "当前Namespace变化了%v", changeEvent.Namespace)
filename := changeEvent.Namespace
if obj, ok := Item2Obj[filename]; ok {

View File

@@ -94,7 +94,6 @@ func (s *Excel) itemsFormat(list []interface{}, Items []string) []interface{} {
if gstr.InArray(Items, k3) {
if _, ok := v3.(string); ok {
list[k2].(g.Map)[k3] = s.Spilt2Item(v3.(string))
} else {
g.Log().Errorf(gctx.New(), "当前类型断言失败:%v,list=%v", v3, v2)
}

View File

@@ -27,7 +27,19 @@ func Excel2Slice(filePath string, _sheet ...string) [][]string {
// 字符串转道具类型
func (s *Excel) Spilt2Item(str string) (result [][]int64) {
parts := strings.Split(str, "|") // 分割字符串
var parts []string
parts1 := strings.Split(str, "|") // 分割字符串
if parts1 == nil {
parts1 = []string{str}
}
for _, v := range parts1 {
parts2 := strings.Split(v, ",") // 分割字符串
if parts2 == nil {
parts = append(parts, v)
} else {
parts = append(parts, parts2...)
}
}
for i := 0; i < len(parts)-1; i += 2 {
num1, _ := strconv.ParseInt(parts[i], 10, 64)

12
go.mod
View File

@@ -5,6 +5,7 @@ go 1.23.0
require (
github.com/apolloconfig/agollo/v4 v4.4.0
github.com/ayflying/excel2json v1.1.2
github.com/gogf/gf/contrib/config/apollo/v2 v2.8.3
github.com/gogf/gf/v2 v2.8.3
github.com/minio/minio-go/v7 v7.0.82
github.com/xuri/excelize/v2 v2.9.0
@@ -25,6 +26,7 @@ require (
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/grokify/html-strip-tags-go v0.1.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
github.com/magiconair/properties v1.8.9 // indirect
@@ -32,12 +34,20 @@ require (
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/mitchellh/mapstructure v1.4.1 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/pelletier/go-toml v1.9.3 // indirect
github.com/richardlehane/mscfb v1.0.4 // indirect
github.com/richardlehane/msoleps v1.0.4 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rs/xid v1.6.0 // indirect
github.com/spf13/afero v1.6.0 // indirect
github.com/spf13/cast v1.3.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.8.1 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/xuri/efp v0.0.0-20240408161823-9ad904a10d6d // indirect
github.com/xuri/nfp v0.0.0-20240318013403-ab9948c2c4a7 // indirect
go.opentelemetry.io/otel v1.24.0 // indirect
@@ -48,5 +58,7 @@ require (
golang.org/x/net v0.32.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

17
go.sum
View File

@@ -43,6 +43,7 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/agiledragon/gomonkey/v2 v2.11.0 h1:5oxSgA+tC1xuGsrIorR+sYiziYltmJyEZ9qA25b6l5U=
github.com/agiledragon/gomonkey/v2 v2.11.0/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/apolloconfig/agollo/v4 v4.4.0 h1:bIIRTEN4f7HgLx97/cNpduEvP9qQ7BkCyDOI2j800VM=
@@ -100,6 +101,7 @@ github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gogf/gf/contrib/config/apollo/v2 v2.8.3/go.mod h1:Uo6f/Pr6zVHSbdP2Lj9iToEMuh/TzU/bE2E5SJlquEk=
github.com/gogf/gf/v2 v2.8.3 h1:h9Px3lqJnnH6It0AqHRz4/1hx0JmvaSf1IvUir5x1rA=
github.com/gogf/gf/v2 v2.8.3/go.mod h1:n++xPYGUUMadw6IygLEgGZqc6y6DRLrJKg5kqCrPLWY=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
@@ -168,6 +170,7 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
@@ -189,6 +192,7 @@ github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/b
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
@@ -199,6 +203,7 @@ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:
github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
@@ -238,6 +243,7 @@ github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS4
github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag=
github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
@@ -247,6 +253,7 @@ github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwd
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ=
github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI=
@@ -268,12 +275,19 @@ github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY=
github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.8.1 h1:Kq1fyeebqsBfbjZj4EL7gj2IO0mMaiyjYUWcUsl2O44=
github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
@@ -285,6 +299,7 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tevid/gohamcrest v1.1.1 h1:ou+xSqlIw1xfGTg1uq1nif/htZ2S3EzRqLm2BP+tYU0=
github.com/tevid/gohamcrest v1.1.1/go.mod h1:3UvtWlqm8j5JbwYZh80D/PVBt0mJ1eJiYgZMibh0H/k=
@@ -647,10 +662,12 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU=
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -45,6 +45,8 @@ func New(_name ...string) *Mod {
name = getName.String()
}
get2, err := g.Cfg().Get(ctx, "s3")
g.Dump(get2)
get, err := g.Cfg().Get(ctx, "s3."+name)
if err != nil {
panic(err.Error())

81
tools/redis.go Normal file
View File

@@ -0,0 +1,81 @@
package tools
import (
"github.com/gogf/gf/v2/database/gredis"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
var (
Redis *redis
)
type redis struct {
}
func (r *redis) Load() {
g.Log().Debugf(gctx.New(), "初始化工具类")
if Redis == nil {
Redis = &redis{}
}
return
}
func (r *redis) RedisScan(cacheKey string, _key ...string) (keys []string, err error) {
var cursor uint64
key := ""
if len(_key) > 0 {
key = _key[0]
}
for {
var newKeys []string
cursor, newKeys, err = g.Redis(key).Scan(ctx, cursor, gredis.ScanOption{
Match: cacheKey,
Count: 1000,
})
if err != nil {
g.Log().Errorf(ctx, "Scan failed: %v", err)
break
}
keys = append(keys, newKeys...)
if cursor == 0 {
break
}
}
return
}
// redis 批量获取大量数据
func (r *redis) RedisScanV2(cacheKey string, _func func([]string) error, _key ...string) error {
//var keys []string
var err error
var cursor uint64
key := ""
if len(_key) > 0 {
key = _key[0]
}
for {
var newKeys []string
cursor, newKeys, err = g.Redis(key).Scan(ctx, cursor, gredis.ScanOption{
Match: cacheKey,
Count: 1000,
})
if err != nil {
g.Log().Errorf(ctx, "Scan failed: %v", err)
break
}
if len(newKeys) > 0 {
err = _func(newKeys)
}
//这个要放在最后
if cursor == 0 {
break
}
}
return err
}

124
tools/time.go Normal file
View File

@@ -0,0 +1,124 @@
package tools
import (
"github.com/gogf/gf/v2/os/gtime"
"time"
)
type timeMod struct {
}
var Time *timeMod
func (m *timeMod) Load() {
if Tools == nil {
Tools = &tools{}
}
}
// 获取本周的开始时间
func (m *timeMod) StartOfWeek(t time.Time) time.Time {
start := gtime.New().AddDate(0, 0, -int(t.Weekday()-1)).Time
start = time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, start.Location())
return start
}
func (m *timeMod) StartOfWeekV2(t time.Time) time.Time {
start := t.AddDate(0, 0, -int(t.Weekday()-1))
start = time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, start.Location())
return start
}
func (m *timeMod) EndOfWeek(t time.Time) time.Time {
return m.StartOfWeek(t).AddDate(0, 0, 7).Add(-(time.Second * 1))
}
// 获取指定时间的0点时间戳
func (m *timeMod) GetTimeDayZero(tm time.Time) time.Time {
duration := time.Hour*time.Duration(tm.Hour()) + time.Minute*time.Duration(tm.Minute()) + time.Second*time.Duration(tm.Second())
return tm.Add(-duration)
}
// GetWeekZero 获取指定时间周一零点的时间
func (m *timeMod) GetWeekZero(now time.Time) time.Time {
timeUnix := m.GetTimeDayZero(now)
now = timeUnix
daysSinceMonday := int(now.Weekday() - time.Monday)
if daysSinceMonday < 0 {
daysSinceMonday += 7
}
currentMonday := now.AddDate(0, 0, -daysSinceMonday)
return currentMonday
}
// 计算两个时间间隔了几天
func (m *timeMod) GetDayPass(startTime time.Time, t ...time.Time) int {
// 获取时间的年、月、日
year := startTime.Year()
month := startTime.Month()
day := startTime.Day()
// 构建一天的开始时间
startTime = time.Date(year, month, day, 0, 0, 0, 0, startTime.Location())
//如果为空,使用当前时间
endTime := time.Now()
if len(t) > 0 {
endTime = t[0]
}
//计算过去了多少天
dayPass := int(endTime.Sub(startTime).Hours() / 24)
return dayPass
}
// 获取下周一的时间
func (m *timeMod) GetNextWeek(now time.Time) time.Time {
now = m.GetWeekZero(now)
timeUnix := now.UnixMilli() + (86400 * 7 * 1000)
nextMondayMidnight := time.UnixMilli(timeUnix)
return nextMondayMidnight
}
// GetDayZeroTime 获取几天后的0点时间
//
// @Description:
// @param currentTime 开始时间
// @param day 多少天后
// @return time.Time
func (m *timeMod) GetDayZeroTime(currentTime time.Time, day int) time.Time {
// 加上指定天数的时间
threeDaysLater := currentTime.AddDate(0, 0, day)
// 调整时间为0点
zeroTime := time.Date(threeDaysLater.Year(), threeDaysLater.Month(), threeDaysLater.Day(), 0, 0, 0, 0, threeDaysLater.Location())
return zeroTime
}
// GetEndTime 获取结束的时间
//
// @Description:
// @receiver m
// @param startTime
// @param _day 多少天以后得实际那,当天时间为空
// @return time.Time
func (m *timeMod) GetEndTime(startTime time.Time, _day ...int) time.Time {
var day = 0
if len(_day) > 0 {
day = _day[0]
}
// 加上指定天数的时间
threeDaysLater := startTime.AddDate(0, 0, day)
// 调整时间为0点
zeroTime := time.Date(threeDaysLater.Year(), threeDaysLater.Month(), threeDaysLater.Day(), 23, 59, 59, 0, threeDaysLater.Location())
return zeroTime
}
// GetDailyTimeList 获取一个时间段里面每天开始的时间
func (m *timeMod) GetDailyTimeList(time1 time.Time, time2 time.Time) (timeList []time.Time) {
day := m.GetDayPass(time1, time2)
timeList = make([]time.Time, day+1)
for i := 0; i <= day; i++ {
//PassDay := i - day
timeList[i] = m.GetDayZeroTime(time1, i)
}
return
}

252
tools/tools.go Normal file
View File

@@ -0,0 +1,252 @@
package tools
import (
bagV1 "game_server/api/bag/v1"
v1 "game_server/api/bag/v1"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gtime"
"math"
"strconv"
"strings"
"time"
)
var (
ctx = gctx.New()
Tools *tools
)
type Number interface {
int | int64 | int32 | int16 | uint64 | uint32 | uint16 | float32 | float64
}
//type Any interface {
// interface{} | string | int | int64 | int32 | int16 | uint64 | uint32 | uint16 | float32 | float64
//}
type toolsInterface interface {
Load()
}
type tools struct {
}
func init() {
g.Log().Debugf(gctx.New(), "初始化工具类")
names := []toolsInterface{
Tools,
}
for _, v := range names {
v.Load()
}
}
func (m *tools) Load() {
if Tools == nil {
Tools = &tools{}
}
}
// 两个时间相隔多少天,需要考虑时区
func (m *tools) GetDay(t1 *gtime.Time, t2 *gtime.Time) int {
if t2 == nil {
t2 = gtime.New(time.UnixMilli(0))
}
return int(t1.Sub(t2).Hours() / 24)
}
// 字符串转道具类型
func (m *tools) Spilt2Item(str string) (result [][]int64) {
parts := strings.Split(str, "|") // 分割字符串
for i := 0; i < len(parts)-1; i += 2 {
num1, _ := strconv.ParseInt(parts[i], 10, 64)
num2, _ := strconv.ParseInt(parts[i+1], 10, 64)
pair := []int64{num1, num2}
result = append(result, pair)
}
return
}
// 切片换道具类型
func (m *tools) Slice2Item(slice []int64) (res [][]int64) {
res = make([][]int64, 0)
for i := 0; i < len(slice)-1; i += 2 {
pair := []int64{slice[i], slice[i+1]}
res = append(res, pair)
}
return res
}
// 道具格式转map
func (m *tools) Items2Map(items [][]int64) (list map[int64]int64) {
list = make(map[int64]int64)
for _, v := range items {
list[v[0]] = v[1]
}
return
}
// 道具转Pb
func (m *tools) Items2Pb(items [][]int64) (list map[int64]*v1.Item) {
list = make(map[int64]*v1.Item)
for _, v := range items {
list[v[0]] = &v1.Item{
Count: v[1],
}
}
return list
}
// UpdateItems 格式化到items输出
func (m *tools) UpdateItems(items [][]int64, updateItems [][]int64, IsDeduct ...bool) (data *bagV1.ItemUpdate) {
data = &bagV1.ItemUpdate{
Items: make(map[int64]*bagV1.Item),
UpdateItems: make(map[int64]*bagV1.Item),
}
for _, v := range items {
if _, ok := data.Items[v[0]]; ok {
//如果存在,追加数据
data.Items[v[0]].Count += v[1]
} else {
//如果不存在,创建数据
data.Items[v[0]] = &bagV1.Item{
Count: v[1],
}
}
}
for _, v := range updateItems {
//UpdateItems 只保存最新的值
data.UpdateItems[v[0]] = &bagV1.Item{
Count: v[1],
}
}
//如果是强制转为负数
if len(IsDeduct) > 0 && IsDeduct[0] {
for k, v := range data.Items {
data.Items[k].Count = -int64(math.Abs(float64(v.Count)))
}
}
return
}
// RemoveSlice 从切片中移除指定的值。
// 参数:
//
// slice: 待操作的切片。
// value: 需要移除的值。
//
// 返回值:
//
// 移除指定值后的切片。
//
// 该函数通过遍历切片,从后向前检查每个元素,如果找到与指定值相等的元素,则将其从切片中移除。
// 这种从后向前的遍历方法可以避免因移除元素而导致的数组重新排列带来的额外计算。
// RemoveSlice 删除切片中的某个值
func RemoveSlice[t Number](slice []t, value t) []t {
// 从后向前遍历切片
for i := len(slice) - 1; i >= 0; i-- {
// 检查当前元素是否等于需要移除的值
if slice[i] == value {
// 如果相等,移除该元素
// 使用append和切片操作符来实现移除操作将i之前和i之后的元素合并到一起
slice = append(slice[:i], slice[i+1:]...)
}
}
// 返回处理后的切片
return slice
}
// InArray 判断当前切片中是否拥有当前值
// InArray[t Number] 支持的类型
//
// @Description:
// @param value 需要查找的值
// @param array 进行查找的切片
// @return bool 返回是否存在
func InArray[t Number](value t, array []t) bool {
for _, v := range array {
if v == value {
return true
}
}
return false
}
// ExtractPage 根据给定的页码和每页大小,从项目切片中提取指定页的项目。
// 它支持泛型,可以用于任何类型的切片。
// 参数:
//
// items: 项目切片,代表所有待分页的项目。
// page: 指定的页码起始页码为1。
// size: 每页的项目数量。
//
// 返回值:
//
// 返回一个切片,包含指定页的项目。
//
// 如果每页大小为0将默认为1。如果项目切片为空或指定页的项目数量少于每页大小且页码大于0则直接返回整个项目切片。
// ExtractPage [t Any]
//
// @Description:
// @param items
// @param page
// @param size
// @return []t
func ExtractPage[t interface{}](items []t, page int, size int) []t {
// 如果每页大小为0将其默认设置为1。
// 如果每页大小为0将其默认设置为1。
if size == 0 {
size = 1
}
// 如果项目切片为空,直接返回空切片。
if len(items) == 0 {
return []t{}
}
//// 如果项目切片长度小于每页大小并且页码大于0返回整个项目切片。
//if len(items) < size && page > 0 {
// //return items
//}
// 计算起始索引和结束索引。
// 根据页码和每页大小计算起始索引和结束索引。
// 计算起始索引和结束索引。
startIndex := (page - 1) * size
endIndex := startIndex + size
// 如果结束索引超出项目切片长度,调整结束索引为项目切片的长度。
// 如果结束索引超出项目切片的长度,将其调整为项目切片的长度。
if endIndex >= len(items) { // 确保不会超出切片范围
endIndex = len(items)
}
// 如果起始索引超出项目切片长度,返回空切片。
if len(items) < startIndex || len(items) < endIndex {
return []t{}
}
// 根据起始索引和结束索引从项目切片中提取指定页的项目,并返回。
// 返回指定页的项目切片。
return items[startIndex:endIndex]
}
// 这是一个用于反转切片的函数示例
// reverseSlice[T comparable]
//
// @Description:
// @param s
// @return []T
func ReverseSlice[T comparable](s []T) []T {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return s
}