Compare commits

..

13 Commits

Author SHA1 Message Date
10ee9bba10 build(go): 移除 go.mod 中所有依赖项声明
清理 go.mod 文件,移除了所有的 require 声明,
包括直接依赖和间接依赖,仅保留模块基本信息。
2025-09-27 00:52:00 +08:00
9f70704081 feat(dependencies): 更新 go.mod 和 go.sum 文件,添加新依赖并优化现有依赖版本
在 go.mod 中添加了多个新依赖,包括用于微服务架构、数据库支持、缓存和消息队列的库。同时,更新了 go.sum 文件以反映这些更改。README.md 文件也进行了相应的更新,增加了微服务架构的描述和功能模块的详细信息,确保文档与代码保持一致。
2025-09-27 00:41:27 +08:00
25386cf0e1 ```
refactor(print): 将 print 包重命名为 printer 并更新所有引用

将项目中的 print 包统一重命名为 printer,以避免与标准库或第三方库产生命名冲突。同时,
更新了所有相关模块对该包的引用,确保功能一致性和代码可维护性。

涉及文件包括:
- conf/new.go
- infra/service.go
- service/register.go
- service/service.go
- with/databases.go
- with/etcd.go
- with/memory.go
- with/redis.go

此外,删除了以下已废弃或未使用的代码文件:
- cmd/cmd.go
- data/map_float.go
- data/map_string.go
- oplog/new.go
- oplog/types.go
- print/print.go
- utils/ext.go
```
2025-09-27 00:20:36 +08:00
21716c4340 ```
feat(database): 自动迁移表结构并优化数据库初始化函数

将 `AutoMigrate` 逻辑从各数据库初始化方法中提取至统一的 `NewDatabase` 方法内,
避免重复代码。同时修改 `Databases`、`Etcd`、`Memory` 和 `RedisCache` 函数签名,
使其返回实例而非通过参数传递,提高代码可读性和一致性。
```
2025-09-23 16:17:03 +08:00
518c237061 fix(conf): 修改YAML解析方式以支持字符串输入
将yaml.Unmarshal的输入从文件字节流改为直接使用yamlString变量,
确保配置解析能够正确处理字符串格式的YAML内容。
2025-09-23 15:04:14 +08:00
139983134b ```
feat(service): 优化地址解析逻辑以支持端口号直接解析

重构 parseTraditionalStyle 函数,简化 NetworkAddress 构造方式,
并引入 utils.IsNumber 判断纯端口号情况,提升地址解析的准确性与兼容性。
```
2025-09-23 13:26:47 +08:00
75aa6ae647 dev 2025-09-23 13:09:27 +08:00
f681f0bb17 ```
refactor(service): 优化Use函数参数类型

移除Use函数中initFunc参数的指针包装,直接使用func() error类型。
简化函数内部调用逻辑,提升代码可读性和健壮性。
```
2025-09-23 12:41:31 +08:00
44319d03b9 ```
refactor(database): 移除全局初始化函数定义

将数据库初始化函数从 database 包中移除,避免全局状态污染。

feat(service): 新增 Use 方法用于执行初始化函数

在 Service 结构体中添加 Use 方法,允许传入并执行初始化函数。
如果函数执行失败,则打印错误并 panic。

refactor(with): 删除旧的初始化逻辑包

删除 with 包中与数据库初始化相关的旧逻辑,统一初始化入口。
```
2025-09-23 12:37:00 +08:00
2f57edd277 ```
refactor(database): 重构数据库初始化逻辑

移除 NewDatabase 函数中的 Init 参数,改用 InitFunc 变量进行初始化操作。
更新 MigrateTables 附近的注释,明确说明 InitFunc 的用途。
删除函数内对 Init 参数的执行逻辑,确保代码简洁性。
```
2025-09-23 11:28:33 +08:00
cf0ee224f7 ```
refactor(database): 调整数据库初始化函数参数传递方式

将 Init 函数参数从全局变量改为通过 NewDatabase 函数参数传入,
使初始化逻辑更清晰、可控。同时优化代码格式,去除多余空行,
提升代码可读性。
```
2025-09-23 11:02:25 +08:00
f2d8ae26f6 build(go): 移除 go.mod 中所有依赖项声明
清理 go.mod 文件,移除了所有直接和间接的依赖项引用,
可能为后续依赖管理或模块重构做准备。
2025-09-22 19:03:20 +08:00
dbf68c38c1 ```
docs(readme): 重构 README 文档结构并补充模块说明

- 重新组织 README 内容,明确划分私有仓库设置、功能模块等章节
- 补充 crypto、cache、database、middleware、queue 和 utils 模块的功能简介
- 统一代码示例格式,增加 bash 和 go 语言标识

feat(crypto): 优化 PKCS7 填充与去填充函数实现

- 新增 PKCS7Padding 和 PKCS7UnPadding 函数的详细注释
- 添加对输入参数的有效性校验,提升健壮性
- 修复可能引发越界 panic 的潜在问题

feat(database): 完善数据库连接及初始化逻辑

- 为 NewDatabase、NewMysql 和 NewPostgres 函数添加完整注释
- 修复 MaxOpenConns 配置未正确赋值的问题
- 在获取 *sql.DB 实例时增加错误处理逻辑
- 支持通过 Init 变量在连接建立后执行自定义初始化函数

feat(go.mod): 初始化项目依赖管理并引入核心组件

- 添加项目所需的主要依赖包,包括 gin、gorm、redis、nats 等
- 引入常用的工具库如 uuid、ulid、gopsutil 等
- 自动拉取并锁定所有间接依赖版本
```
2025-09-22 19:02:38 +08:00
28 changed files with 888 additions and 206 deletions

238
README.md
View File

@@ -1,27 +1,223 @@
# 私有仓库core 设置
```
# BSM-SDK Core
BSM-SDK Core 是一个企业级后端开发工具包的核心模块,提供了微服务架构、配置管理、加密解密、缓存、数据库访问、中间件等基础功能。
## 私有仓库设置
```bash
go env -w GOPRIVATE=git.apinb.com/*
go env -w GONOPROXY=git.apinb.com/*
go env -w GOINSECURE=git.apinb.com/*
go env -w GONOSUMDB=git.apinb.com/*
```
# crypto 加密与解密
## GCM加密
```
AESGCMEncrypt GCM 加密
AESGCMDecrypt GCM 解密
```
## CBC加密
```
Encrypt CBC加密
Decrypt CBC解密
```
## ECB加密
```
AesEncryptECB ECB加密
AesDecryptECB ECB解密
```
## 环境变量检测
```
AesKeyCheck 秘钥环境变量检测
## 核心功能模块
### 1. 服务管理 (service)
#### 服务启动与注册
- **Service**: 核心服务结构,支持 gRPC 服务启动和 etcd 注册
- **New()**: 创建服务实例
- **Start()**: 启动服务,支持 etcd 注册和 HTTP 网关
- **Stop()**: 优雅停止服务
- **Use()**: 执行初始化函数
#### 服务发现
- **FoundGrpcMethods()**: 自动发现 gRPC 方法
- **RegisterService()**: 注册服务到 etcd
- **ServiceRegister**: 服务注册器,支持租约管理
#### 元数据解析
- **ParseMetaCtx()**: 解析 gRPC 上下文中的元数据
- **ParseOptions**: 解析选项支持角色验证和私有IP检查
### 2. 配置管理 (conf)
#### 配置加载
- **New()**: 加载配置文件,支持环境变量替换
- **NotNil()**: 验证必需配置项
- **PrintInfo()**: 打印配置信息
- **CheckPort()**: 检查端口配置
#### 配置类型
- **MicroServiceConf**: 微服务配置
- **GatewayConf**: 网关配置
- **DBConf**: 数据库配置
### 3. 加密与解密 (crypto)
#### AES 加密
- **AESGCMEncrypt/AESGCMDecrypt**: GCM 模式加密解密
- **Encrypt/Decrypt**: CBC 模式加密解密
- **AesEncryptECB/AesDecryptECB**: ECB 模式加密解密
- **AesKeyCheck()**: 密钥环境变量检测
#### RSA 加密
- **EncryptWithPublicKey()**: 公钥加密
- **Decrypt()**: 私钥解密
#### 通用加密
- **AesEncryptCBC/AesDecryptCBC**: 通用 CBC 加密解密
- **PKCS7Padding/PKCS7UnPadding**: PKCS7 填充
### 4. 数据库支持 (database)
#### 数据库连接
- **NewDatabase()**: 创建数据库连接,支持 MySQL 和 PostgreSQL
- **NewMysql()**: MySQL 连接
- **NewPostgres()**: PostgreSQL 连接
#### 数据库类型
- **SqlOptions**: 数据库连接选项
- **Std_IICUDS**: 标准数据库模型ID、Identity、Created、Updated、Deleted、Status
- **Std_ICUD**: 标准数据库模型ID、Created、Updated、Deleted
- **Std_Passport**: 护照模型
- **Std_Owner**: 所有者模型
### 5. 缓存支持 (cache)
#### Redis 缓存
- **RedisClient**: Redis 客户端封装
- **New()**: 创建 Redis 连接
- **Hash()**: 哈希分片计算
#### 内存缓存
- 支持内存缓存操作
### 6. 消息队列 (queue)
#### NATS 消息队列
- **Nats**: NATS 客户端封装
- **NewNats()**: 创建 NATS 连接
- **Subscribe()**: 订阅消息
- **Producer()**: 发布消息
### 7. 中间件 (middleware)
#### JWT 认证
- **JwtAuth()**: JWT 认证中间件
- **ParseAuth()**: 解析认证信息
#### CORS 支持
- **Cors()**: CORS 中间件
#### 运行模式
- **Mode()**: 设置 Gin 运行模式
### 8. 工具类 (utils)
#### 网络工具
- **GetLocationIP()**: 获取本机IP
- **IsPublicIP()**: 判断是否为公网IP
- **HttpGet/HttpPost()**: HTTP 请求工具
- **DownloadFile()**: 文件下载
#### 数据类型转换
- **String2Int/String2Int64**: 字符串转整数
- **String2Float64/String2Float32**: 字符串转浮点数
- **Int2String/Int642String**: 整数转字符串
- **Float64ToString/Float32ToString**: 浮点数转字符串
- **AnyToString()**: 任意类型转字符串
#### 时间处理
- **Time2String()**: 时间转字符串
- **String2Time()**: 字符串转时间
#### 身份标识
- **UUID()**: 生成 UUID
- **ULID()**: 生成 ULID
#### 文件操作
- **PathExists()**: 检查路径是否存在
- **CreateDir()**: 创建目录
- **GetRunPath()**: 获取运行路径
- **GetCurrentPath()**: 获取当前路径
#### JSON 处理
- **JsonEscape()**: JSON 转义
### 9. 错误处理 (errcode)
#### 标准错误码
- **Header 错误**: 101-104
- **标准错误**: 110-121
- **JWT 错误**: 131-139
- **模型错误**: 151-157
- **gRPC 错误**: 171-186
#### 错误创建
- **NewError()**: 创建标准错误
- **ErrFatal()**: 创建致命错误
- **ErrNotFound()**: 创建未找到错误
### 10. 响应处理 (infra)
#### 统一响应
- **Reply**: 统一响应结构
- **Success()**: 成功响应
- **Error()**: 错误响应,支持 gRPC 状态码转换
### 11. 日志打印 (printer)
#### 彩色日志
- **Info()**: 信息日志(白色)
- **Warn()**: 警告日志(橙色)
- **Success()**: 成功日志(绿色)
- **Error()**: 错误日志(红色)
- **Json()**: JSON 格式化输出
### 12. 环境管理 (env)
#### 运行时环境
- **RuntimeEnv**: 运行时环境配置
- **NewEnv()**: 初始化环境
- **GetEnvDefault()**: 获取环境变量默认值
### 13. 变量管理 (vars)
#### 全局变量
- **ServiceKey**: 服务键
- **HostName**: 主机名
- **VERSION**: 版本号
- **BUILD_TIME**: 构建时间
- **GO_VERSION**: Go 版本
### 14. 第三方集成 (third)
#### 微信集成
- 支持微信相关功能
### 15. 许可证管理 (licence)
#### 许可证验证
- 支持许可证文件验证
### 配置环境变量
```bash
export BSM_Workspace=def
export BSM_JwtSecretKey=your_secret_key
export BSM_RuntimeMode=dev
export BSM_Prefix=/usr/local/bsm
```
### 安全建议
- 使用强密钥进行加密
- 定期更新 JWT 密钥
- 配置适当的数据库连接池
- 使用 HTTPS 进行通信
- 定期检查许可证有效性
## 许可证
本项目采用私有许可证,请确保已获得相应的使用授权。
## 贡献
欢迎提交 Issue 和 Pull Request 来改进本项目。
## 联系方式
如有问题,请联系开发团队。

View File

@@ -1,34 +1,32 @@
package data
package mapsync
import (
"sync"
)
var (
// Cache
CacheMapFloat *MapFloat
// sync map
MapFloat *mapFloat
)
// lock
type MapFloat struct {
type mapFloat struct {
sync.RWMutex
Data map[string]float64
}
func NewMapFloat() *MapFloat {
return &MapFloat{
func NewMapFloat() *mapFloat {
return &mapFloat{
Data: make(map[string]float64),
}
}
func (c *MapFloat) All() map[string]float64 {
c.RLock()
defer c.RUnlock()
return c.Data
func (c *mapFloat) Set(key string, val float64) {
c.Lock()
defer c.Unlock()
c.Data[key] = val
}
func (c *MapFloat) Get(key string) float64 {
func (c *mapFloat) Get(key string) float64 {
c.RLock()
defer c.RUnlock()
@@ -40,13 +38,14 @@ func (c *MapFloat) Get(key string) float64 {
return vals
}
func (c *MapFloat) Set(key string, val float64) {
func (c *mapFloat) Del(key string) {
c.Lock()
defer c.Unlock()
c.Data[key] = val
delete(c.Data, key)
}
func (c *MapFloat) Keys() (keys []string) {
func (c *mapFloat) Keys() (keys []string) {
c.RLock()
defer c.RUnlock()
@@ -56,3 +55,10 @@ func (c *MapFloat) Keys() (keys []string) {
return
}
func (c *mapFloat) All() map[string]float64 {
c.RLock()
defer c.RUnlock()
return c.Data
}

64
cache/mapsync/map_int.go vendored Normal file
View File

@@ -0,0 +1,64 @@
package mapsync
import (
"sync"
)
var (
// sync map
MapInt *mapInt
)
// lock
type mapInt struct {
sync.RWMutex
Data map[string]int
}
func NewMapInt() *mapInt {
return &mapInt{
Data: make(map[string]int),
}
}
func (c *mapInt) Set(key string, val int) {
c.Lock()
defer c.Unlock()
c.Data[key] = val
}
func (c *mapInt) Get(key string) int {
c.RLock()
defer c.RUnlock()
vals, ok := c.Data[key]
if !ok {
return 0
}
return vals
}
func (c *mapInt) Del(key string) {
c.Lock()
defer c.Unlock()
delete(c.Data, key)
}
func (c *mapInt) All() map[string]int {
c.RLock()
defer c.RUnlock()
return c.Data
}
func (c *mapInt) Keys() (keys []string) {
c.RLock()
defer c.RUnlock()
for k, _ := range c.Data {
keys = append(keys, k)
}
return
}

64
cache/mapsync/map_string.go vendored Normal file
View File

@@ -0,0 +1,64 @@
package mapsync
import (
"sync"
)
var (
// sync map
MapString *mapString
)
// lock
type mapString struct {
sync.RWMutex
Data map[string]string
}
func NewMapString() *mapString {
return &mapString{
Data: make(map[string]string),
}
}
func (c *mapString) Set(key, val string) {
c.Lock()
defer c.Unlock()
c.Data[key] = val
}
func (c *mapString) Get(key string) string {
c.RLock()
defer c.RUnlock()
vals, ok := c.Data[key]
if !ok {
return ""
}
return vals
}
func (c *mapString) Del(key string) {
c.Lock()
defer c.Unlock()
delete(c.Data, key)
}
func (c *mapString) Keys() (keys []string) {
c.RLock()
defer c.RUnlock()
for k, _ := range c.Data {
keys = append(keys, k)
}
return
}
func (c *mapString) All() map[string]string {
c.RLock()
defer c.RUnlock()
return c.Data
}

View File

@@ -11,7 +11,7 @@ import (
"math/rand/v2"
"git.apinb.com/bsm-sdk/core/env"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/utils"
"git.apinb.com/bsm-sdk/core/vars"
yaml "gopkg.in/yaml.v3"
@@ -36,8 +36,8 @@ func New(srvKey string, cfg any) {
cfp = filepath.Join(env.Runtime.Prefix, "etc", cfp)
}
print.Info("[BSM - %s] Config File: %s", srvKey, cfp)
print.Info("[BSM - %s] Check Configure ...", vars.ServiceKey)
printer.Info("[BSM - %s] Config File: %s", srvKey, cfp)
printer.Info("[BSM - %s] Check Configure ...", vars.ServiceKey)
// 读取配置文件内容
yamlFile, err := os.ReadFile(cfp)
@@ -54,7 +54,7 @@ func New(srvKey string, cfg any) {
}
// 解析YAML
err = yaml.Unmarshal(yamlFile, cfg)
err = yaml.Unmarshal([]byte(yamlString), cfg)
if err != nil {
log.Fatalf("ERROR: %v", err)
}
@@ -69,9 +69,9 @@ func NotNil(values ...string) {
}
func PrintInfo(addr string) {
print.Success("[BSM - %s] Config Check Success.", vars.ServiceKey)
print.Info("[BSM - %s] Service Name: %s", vars.ServiceKey, vars.ServiceKey)
print.Info("[BSM - %s] Runtime Mode: %s", vars.ServiceKey, env.Runtime.Mode)
printer.Success("[BSM - %s] Config Check Success.", vars.ServiceKey)
printer.Info("[BSM - %s] Service Name: %s", vars.ServiceKey, vars.ServiceKey)
printer.Info("[BSM - %s] Runtime Mode: %s", vars.ServiceKey, env.Runtime.Mode)
}
func CheckPort(port string) string {

View File

@@ -155,8 +155,9 @@ func AesKeyCheck(key string) (string, error) {
// 从环境变量获取密钥
keyHex := os.Getenv(key)
if keyHex == "" {
fmt.Println("环境变量 RST_KEY 未设置")
return "", errors.New("环境变量 RST_KEY 未设置")
// 使用入参作为变量名,避免硬编码误导
fmt.Printf("环境变量 %s 未设置\n", key)
return "", errors.New("密钥环境变量未设置")
}
// 解码十六进制字符串的密钥
byteKey, err := hex.DecodeString(keyHex)
@@ -165,8 +166,8 @@ func AesKeyCheck(key string) (string, error) {
return "", errors.New("密钥解码失败")
}
// 检查密钥长度
if len(byteKey) != 16 && len(key) != 24 && len(key) != 32 {
fmt.Printf("无效的密钥长度: %d 字节 (需要16,24或32字节)\n", len(key))
if len(byteKey) != 16 && len(byteKey) != 24 && len(byteKey) != 32 {
fmt.Printf("无效的密钥长度: %d 字节 (需要16,24或32字节)\n", len(byteKey))
return "", errors.New("无效的密钥长度,需要16,24或32字节")
}
return keyHex, nil

View File

@@ -104,31 +104,41 @@ func AesDecryptCBC(cryted string) (b []byte, err error) {
return orig, nil
}
// PKCS7Padding 使用PKCS7填充法对明文进行填充
func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
padding := blocksize - len(ciphertext)%blocksize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
// 去码
// PKCS7UnPadding 去除PKCS7填充
// bug:runtime error: slice bounds out of range [:-22]
func PKCS7UnPadding(origData []byte, blocksize int) []byte {
// 检查块大小是否有效
if blocksize <= 0 {
return nil
}
// 检查原始数据是否为空
if origData == nil || len(origData) == 0 {
return nil
}
// 检查数据长度是否为块大小的整数倍
if len(origData)%blocksize != 0 {
return nil
}
length := len(origData)
// 获取填充字节数
unpadding := int(origData[length-1])
// 检查去填充后数据长度是否有效
if length-unpadding <= 0 {
return nil
}
// 返回去除填充后的数据
return origData[:(length - unpadding)]
}

View File

@@ -1,51 +0,0 @@
package data
import (
"sync"
)
var (
// Cache
CacheMapString *MapString
)
// lock
type MapString struct {
sync.RWMutex
Data map[string]string
}
func NewMapString() *MapString {
return &MapString{
Data: make(map[string]string),
}
}
func (c *MapString) Get(key string) string {
c.RLock()
defer c.RUnlock()
vals, ok := c.Data[key]
if !ok {
return ""
}
return vals
}
func (c *MapString) Set(key, val string) {
c.Lock()
defer c.Unlock()
c.Data[key] = val
}
func (c *MapString) Keys() (keys []string) {
c.RLock()
defer c.RUnlock()
for k, _ := range c.Data {
keys = append(keys, k)
}
return
}

View File

@@ -1,3 +1,4 @@
// Package database provides database connection and management functionality
package database
import (
@@ -12,9 +13,12 @@ import (
)
var (
// MigrateTables holds the tables that need to be auto-migrated on database initialization
MigrateTables []any
)
// NewDatabase creates a new database connection based on the provided driver type
// It supports both MySQL and PostgreSQL databases
func NewDatabase(driver string, dsn []string, options *types.SqlOptions) (db *gorm.DB, err error) {
driver = strings.ToLower(driver)
switch driver {
@@ -30,16 +34,24 @@ func NewDatabase(driver string, dsn []string, options *types.SqlOptions) (db *go
return nil, err
}
// auto migrate table.
if len(MigrateTables) > 0 {
err = db.AutoMigrate(MigrateTables...)
if err != nil {
return nil, err
}
}
return db, nil
}
// NewMysql 创建MySQL数据库服务
// NewMysql creates a MySQL database service
func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) {
//set connection default val.
if options == nil {
options = &types.SqlOptions{
MaxIdleConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxOpenConns,
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
LogStdout: false,
Debug: true,
@@ -58,7 +70,11 @@ func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err err
}
// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
sqlDB, _ := gormDb.DB()
sqlDB, err := gormDb.DB()
if err != nil {
return nil, err
}
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
sqlDB.SetMaxIdleConns(options.MaxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
@@ -66,23 +82,16 @@ func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err err
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
if len(MigrateTables) > 0 {
err = gormDb.AutoMigrate(MigrateTables...)
if err != nil {
return nil, err
}
}
return gormDb, nil
}
// NewPostgres 创建PostgreSQL数据库服务
// NewPostgres creates a PostgreSQL database service
func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) {
//set connection default val.
if options == nil {
options = &types.SqlOptions{
MaxIdleConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxOpenConns,
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
LogStdout: false,
Debug: true,
@@ -98,12 +107,18 @@ func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err
gormDb = gormDb.Debug()
}
if len(MigrateTables) > 0 {
err = gormDb.AutoMigrate(MigrateTables...)
// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
sqlDB, err := gormDb.DB()
if err != nil {
return nil, err
}
}
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
sqlDB.SetMaxIdleConns(options.MaxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(options.MaxOpenConns)
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
return
}

View File

@@ -12,7 +12,7 @@ func SetOptions(options *types.SqlOptions) *types.SqlOptions {
if options == nil {
options = &types.SqlOptions{
MaxIdleConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxOpenConns,
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
LogStdout: false,
Debug: false,
@@ -30,7 +30,7 @@ func NewPostgreSql(dsn string, options *types.SqlOptions) (*gorm.DB, error) {
if options == nil {
options = &types.SqlOptions{
MaxIdleConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxOpenConns,
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
LogStdout: false,
Debug: true,
@@ -56,7 +56,11 @@ func NewPostgreSql(dsn string, options *types.SqlOptions) (*gorm.DB, error) {
}
// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
sqlDB, _ := gormDb.DB()
sqlDB, err := gormDb.DB()
if err != nil {
return nil, err
}
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
sqlDB.SetMaxIdleConns(options.MaxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。

View File

@@ -1,4 +1,10 @@
package oplog
package infra
import (
"encoding/json"
"git.apinb.com/bsm-sdk/core/utils"
)
type LogItem struct {
OpID uint `json:"op_id"`
@@ -22,3 +28,10 @@ var (
Type_Other string = "other"
Type_Create string = "create"
)
func NewLogs(endpoint string, data []*LogItem) {
jsonBytes, _ := json.Marshal(data)
go utils.HttpPost(endpoint, nil, jsonBytes)
}

View File

@@ -13,6 +13,7 @@ type Reply struct {
Result any `json:"result"`
}
// Success writes a normalized success payload with code=0.
func (reply *Reply) Success(ctx *gin.Context, data any) {
reply.Code = 0
reply.Result = data
@@ -22,6 +23,9 @@ func (reply *Reply) Success(ctx *gin.Context, data any) {
}
ctx.JSON(200, reply)
}
// Error converts an error (including gRPC status) to a normalized payload.
// Error converts an error (including gRPC status) to a normalized payload.
func (reply *Reply) Error(ctx *gin.Context, err error) {
reply.Code = 500
reply.Result = ""
@@ -29,8 +33,10 @@ func (reply *Reply) Error(ctx *gin.Context, err error) {
e, ok := status.FromError(err)
if ok {
reply.Code = int32(e.Code())
}
reply.Message = e.Message()
} else {
reply.Message = err.Error()
}
// Send error
ctx.JSON(200, reply)

View File

@@ -5,7 +5,7 @@ import (
"log"
"time"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/utils"
clientv3 "go.etcd.io/etcd/client/v3"
)
@@ -37,10 +37,10 @@ func (s *service) Register(cli *clientv3.Client, serviceName string, port string
return err
}
print.Info("[BSM Register] Service Key: %s", key)
print.Info("[BSM Register] Service Val: %s", serviceAddr)
printer.Info("[BSM Register] Service Key: %s", key)
printer.Info("[BSM Register] Service Val: %s", serviceAddr)
print.Success("[BSM Register] Service Register Complete.")
printer.Success("[BSM Register] Service Register Complete.")
go func() {
for keepAliveResp := range keepAliveChan {

View File

@@ -1,14 +0,0 @@
package oplog
import (
"encoding/json"
"git.apinb.com/bsm-sdk/core/utils"
)
func New(endpoint string, data []*LogItem) {
jsonBytes, _ := json.Marshal(data)
go utils.HttpPost(endpoint, nil, jsonBytes)
}

View File

@@ -1,6 +1,8 @@
package print
package printer
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
@@ -36,3 +38,11 @@ func Error(format string, a ...interface{}) {
message := fmt.Sprintf("\033[31m[Error] "+format+"\033[0m\n", a...)
logger.Print(message)
}
func Json(v any) {
jsonBy, _ := json.Marshal(v)
var out bytes.Buffer
json.Indent(&out, jsonBy, "", "\t")
out.WriteTo(os.Stdout)
fmt.Printf("\n")
}

204
service/address.go Normal file
View File

@@ -0,0 +1,204 @@
package service
import (
"fmt"
"net"
"net/url"
"strings"
"git.apinb.com/bsm-sdk/core/utils"
)
type NetworkAddress struct {
Protocol string // tcp, tcp4, tcp6, unix, unixpacket
Host string // IP 地址或主机名
Port string // 端口号
Path string // Unix socket 路径
Raw string // 原始字符串
}
// 解析网络地址字符串
// "tcp://0.0.0.0:1212",
//
// "tcp4://127.0.0.1:8080",
// "tcp6://[::1]:8080",
// "unix:///data/app/passport.sock",
// "unixpacket:///tmp/mysql.sock",
// ":8080", // 传统格式
// "/tmp/server.sock", // 传统Unix格式
// "invalid://address", // 错误格式
func ParseNetworkAddress(addr string) (*NetworkAddress, error) {
// 如果包含 ://,按 URL 解析
if strings.Contains(addr, "://") {
return parseURLStyle(addr)
}
// 否则按传统格式解析
return parseTraditionalStyle(addr)
}
// 解析 tcp://0.0.0.0:1212 或 unix:///path/to/socket 格式
func parseURLStyle(addr string) (*NetworkAddress, error) {
u, err := url.Parse(addr)
if err != nil {
return nil, fmt.Errorf("解析URL失败: %w", err)
}
result := &NetworkAddress{
Protocol: u.Scheme,
Raw: addr,
}
switch u.Scheme {
case "tcp", "tcp4", "tcp6":
return parseTCPURL(u, result)
case "unix", "unixpacket":
return parseUnixURL(u, result)
default:
return nil, fmt.Errorf("不支持的协议: %s", u.Scheme)
}
}
// 解析 TCP 类型的 URL
func parseTCPURL(u *url.URL, result *NetworkAddress) (*NetworkAddress, error) {
host, port, err := net.SplitHostPort(u.Host)
if err != nil {
// 如果没有端口,尝试添加默认端口
if strings.Contains(err.Error(), "missing port") {
host = u.Host
port = "0" // 默认端口
} else {
return nil, fmt.Errorf("解析TCP地址失败: %w", err)
}
}
result.Host = host
result.Port = port
// 根据主机地址确定具体的协议类型
if result.Protocol == "tcp" {
result.Protocol = determineTCPProtocol(host)
}
return result, nil
}
// 解析 Unix socket 类型的 URL
func parseUnixURL(u *url.URL, result *NetworkAddress) (*NetworkAddress, error) {
// Unix socket 路径在 URL 的 Path 字段
if u.Path == "" {
return nil, fmt.Errorf("Unix socket 路径不能为空")
}
result.Path = u.Path
// 如果协议是 unix但路径表明需要数据包传输可以自动升级
if result.Protocol == "unix" && strings.Contains(u.Path, "packet") {
result.Protocol = "unixpacket"
}
return result, nil
}
// 根据主机地址确定 TCP 协议类型
func determineTCPProtocol(host string) string {
if host == "" {
return "tcp" // 默认
}
// 解析 IP 地址
ip := net.ParseIP(host)
if ip != nil {
if ip.To4() != nil {
return "tcp4"
}
return "tcp6"
}
// 如果是特殊地址
switch host {
case "0.0.0.0", "127.0.0.1", "localhost":
return "tcp4"
case "::", "::1":
return "tcp6"
default:
return "tcp" // 默认支持双栈
}
}
// 解析传统格式如 ":8080", "127.0.0.1:8080", "/tmp/socket"
func parseTraditionalStyle(addr string) (*NetworkAddress, error) {
// 检查是否是 Unix socket包含路径分隔符
if strings.Contains(addr, "/") || strings.HasPrefix(addr, "@/") {
return &NetworkAddress{Protocol: "unix", Path: addr}, nil
}
// 否则按 TCP 地址解析
host, port, err := net.SplitHostPort(addr)
if err == nil {
return &NetworkAddress{Protocol: "tcp", Host: host, Port: port}, nil
}
// 检查是否是端口号
if ok := utils.IsNumber(addr); ok {
return &NetworkAddress{Protocol: "tcp", Host: "0.0.0.0", Port: addr}, nil
}
return nil, fmt.Errorf("解析地址失败: %w", err)
}
// 获取网络类型用于 net.Dial 或 net.Listen
func (na *NetworkAddress) Network() string {
return na.Protocol
}
// 获取地址字符串用于 net.Dial 或 net.Listen
func (na *NetworkAddress) Address() string {
switch na.Protocol {
case "tcp", "tcp4", "tcp6":
if na.Port == "" {
return na.Host
}
return net.JoinHostPort(na.Host, na.Port)
case "unix", "unixpacket":
return na.Path
default:
return na.Raw
}
}
// 格式化输出
func (na *NetworkAddress) String() string {
switch na.Protocol {
case "tcp", "tcp4", "tcp6":
return fmt.Sprintf("%s://%s", na.Protocol, net.JoinHostPort(na.Host, na.Port))
case "unix", "unixpacket":
return fmt.Sprintf("%s://%s", na.Protocol, na.Path)
default:
return na.Raw
}
}
// 验证地址是否有效
func (na *NetworkAddress) Validate() error {
switch na.Protocol {
case "tcp", "tcp4", "tcp6":
if na.Host == "" && na.Port == "" {
return fmt.Errorf("TCP地址需要主机和端口")
}
// 验证端口
if na.Port != "" {
if _, err := net.LookupPort("tcp", na.Port); err != nil {
return fmt.Errorf("无效的端口: %s", na.Port)
}
}
case "unix", "unixpacket":
if na.Path == "" {
return fmt.Errorf("Unix socket路径不能为空")
}
default:
return fmt.Errorf("不支持的协议: %s", na.Protocol)
}
return nil
}

View File

@@ -1,4 +1,4 @@
package cmd
package service
import (
"fmt"

View File

@@ -5,7 +5,7 @@ import (
"strings"
"time"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/vars"
clientv3 "go.etcd.io/etcd/client/v3"
)
@@ -94,7 +94,11 @@ func (s *ServiceRegister) Close() error {
func (s *ServiceRegister) SetAnonymous(key string, urls []string) {
// remove reppeat, clear service all anonymous uri.
anonymous, _ := s.cli.Get(context.Background(), key)
anonymous, err := s.cli.Get(context.Background(), key)
if err != nil {
printer.Error("[BSM Register] Get Anonymous Fail: %v", err)
return
}
var as []string
if len(anonymous.Kvs) > 0 {
@@ -106,12 +110,12 @@ func (s *ServiceRegister) SetAnonymous(key string, urls []string) {
newAnonymous := strings.Join(as, ",")
// put anonymous to etcd
_, err := s.cli.Put(context.Background(), key, newAnonymous)
_, err = s.cli.Put(context.Background(), key, newAnonymous)
if err != nil {
print.Error("[BSM Register] Anonymous Fail.")
printer.Error("[BSM Register] Anonymous Fail.")
} else {
print.Info("[BSM Register] Anonymous: %s", newAnonymous)
printer.Info("[BSM Register] Anonymous: %s", newAnonymous)
}
}

View File

@@ -14,7 +14,7 @@ import (
"git.apinb.com/bsm-sdk/core/conf"
"git.apinb.com/bsm-sdk/core/env"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/vars"
clientv3 "go.etcd.io/etcd/client/v3"
"google.golang.org/grpc"
@@ -43,27 +43,28 @@ func New(srv *grpc.Server, opts *Options) *Service {
return &Service{GrpcSrv: srv, Opts: opts}
}
// Addr formats ip and port into host:port.
func Addr(ip string, port int) string {
return net.JoinHostPort(ip, strconv.Itoa(port))
}
func (s *Service) Start() {
print.Info("[BSM - %s] Service Starting ...", vars.ServiceKey)
printer.Info("[BSM - %s] Service Starting ...", vars.ServiceKey)
// register to etcd.
if s.Opts.MsConf != nil && s.Opts.MsConf.Enable {
if s.Opts.EtcdClient == nil {
print.Error("[BSM Register] Etcd Client is nil.")
printer.Error("[BSM Register] Etcd Client is nil.")
os.Exit(1)
}
print.Info("[BSM - %s] Registering Service to Etcd ...", vars.ServiceKey)
// get methods
printer.Info("[BSM - %s] Registering Service to Etcd ...", vars.ServiceKey)
// get methods for gateway/router discovery
methods := FoundGrpcMethods(s.GrpcSrv)
// set router key
routerKey := vars.ServiceRootPrefix + "Router/" + env.Runtime.Workspace + "/" + strings.ToLower(vars.ServiceKey) + "/" + s.Opts.Addr
// register to etcd
// register to etcd with lease
register, err := RegisterService(s.Opts.EtcdClient, routerKey, methods, vars.ServiceLease)
if err != nil {
log.Panicf("[ERROR] %s Service Register:%s \n", vars.ServiceKey, err.Error())
@@ -88,13 +89,13 @@ func (s *Service) Start() {
panic(err)
}
}()
print.Success("[BSM - %s] Grpc %s Runing Success !", vars.ServiceKey, s.Opts.Addr)
printer.Success("[BSM - %s] Grpc %s Runing Success !", vars.ServiceKey, s.Opts.Addr)
if s.Opts.GatewayConf != nil && s.Opts.GatewayConf.Enable {
addr := Addr("0.0.0.0", s.Opts.GatewayConf.Port)
go s.Gateway(s.Opts.Addr, addr)
print.Success("[BSM - %s] Http %s Runing Success!", vars.ServiceKey, addr)
printer.Success("[BSM - %s] Http %s Runing Success!", vars.ServiceKey, addr)
}
select {}
@@ -105,7 +106,18 @@ func (s *Service) Gateway(grpcAddr string, httpAddr string) {
_, cancel := context.WithCancel(s.Opts.GatewayCtx)
defer cancel()
http.ListenAndServe(httpAddr, s.Opts.GatewayMux)
// 不因 HTTP 启动失败而导致 panic
if err := http.ListenAndServe(httpAddr, s.Opts.GatewayMux); err != nil {
printer.Error("[BSM - %s] Http Serve Error: %v", vars.ServiceKey, err)
}
}
func (s *Service) Use(initFunc func() error) {
err := (initFunc)()
if err != nil {
printer.Error(err.Error())
panic(err)
}
}
func (s *Service) Stop() {

View File

@@ -6,36 +6,48 @@ import (
"strings"
)
// 字符串转Int
// String2Int 字符串转Int
//
// intStr数字的字符串
func String2Int(intStr string) (intNum int) {
intNum, _ = strconv.Atoi(intStr)
intNum, err := strconv.Atoi(intStr)
if err != nil {
return 0
}
return
}
// 字符串转Int64
// String2Int64 字符串转Int64
//
// intStr数字的字符串
func String2Int64(intStr string) (int64Num int64) {
intNum, _ := strconv.Atoi(intStr)
intNum, err := strconv.Atoi(intStr)
if err != nil {
return 0
}
int64Num = int64(intNum)
return
}
// 字符串转Float64
// String2Float64 字符串转Float64
//
// floatStr小数点数字的字符串
func String2Float64(floatStr string) (floatNum float64) {
floatNum, _ = strconv.ParseFloat(floatStr, 64)
floatNum, err := strconv.ParseFloat(floatStr, 64)
if err != nil {
return 0
}
return
}
// 字符串转Float32
// String2Float32 字符串转Float32
//
// floatStr小数点数字的字符串
func String2Float32(floatStr string) (floatNum float32) {
floatNum64, _ := strconv.ParseFloat(floatStr, 32)
floatNum64, err := strconv.ParseFloat(floatStr, 32)
if err != nil {
return 0
}
floatNum = float32(floatNum64)
return
}

View File

@@ -25,11 +25,17 @@ func CreateDir(dirName string) bool {
}
func GetRunPath() string {
path, _ := os.Executable()
path, err := os.Executable()
if err != nil {
return ""
}
return path
}
func GetCurrentPath() string {
path, _ := os.Getwd()
path, err := os.Getwd()
if err != nil {
return ""
}
return path
}

View File

@@ -1,10 +1,6 @@
package utils
import (
"bytes"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
)
@@ -37,11 +33,3 @@ func ParseParams(in map[string]string) map[string]interface{} {
}
return out
}
func PrintJson(v any) {
jsonBy, _ := json.Marshal(v)
var out bytes.Buffer
json.Indent(&out, jsonBy, "", "\t")
out.WriteTo(os.Stdout)
fmt.Printf("\n")
}

View File

@@ -195,7 +195,7 @@ func DownloadFile(url, saveTo string, fb func(length, downLen int64)) {
resp, err := client.Get(url)
if err != nil {
fmt.Printf("download %s error:%s\n", url, err)
os.Exit(0)
return
}
//读取服务器返回的文件大小
fsize, err = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 32)
@@ -207,12 +207,12 @@ func DownloadFile(url, saveTo string, fb func(length, downLen int64)) {
file.Chmod(0777)
if err != nil {
fmt.Printf("Create %s error:%s\n", saveTo, err)
os.Exit(0)
return
}
defer file.Close()
if resp.Body == nil {
fmt.Printf("resp %s error:%s\n", url, err)
os.Exit(0)
return
}
defer resp.Body.Close()
//下面是 io.copyBuffer() 的简化版本
@@ -250,6 +250,6 @@ func DownloadFile(url, saveTo string, fb func(length, downLen int64)) {
if err != nil {
fmt.Printf("callback error:%s\n", err)
os.Exit(0)
return
}
}

129
utils/validator.go Normal file
View File

@@ -0,0 +1,129 @@
package utils
import (
"regexp"
"strings"
"unicode"
)
// IsEmail 验证是否是邮箱格式
func IsEmail(email string) bool {
if strings.TrimSpace(email) == "" {
return false
}
// 邮箱正则表达式
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
matched, err := regexp.MatchString(pattern, email)
if err != nil {
return false
}
return matched
}
// IsMobile 验证是否是手机号(中国手机号格式)
func IsMobile(mobile string) bool {
if strings.TrimSpace(mobile) == "" {
return false
}
// 中国手机号正则表达式1开头第二位3-9后面9位数字
pattern := `^1[3-9]\d{9}$`
matched, err := regexp.MatchString(pattern, mobile)
if err != nil {
return false
}
return matched
}
// IsNumber 验证是否是纯数字
func IsNumber(str string) bool {
if strings.TrimSpace(str) == "" {
return false
}
for _, char := range str {
if !unicode.IsDigit(char) {
return false
}
}
return true
}
// IsEnglish 验证是否是英文字符(不限大小写)
func IsEnglish(str string) bool {
if strings.TrimSpace(str) == "" {
return false
}
for _, char := range str {
if !unicode.IsLetter(char) {
return false
}
if !isEnglishLetter(char) {
return false
}
}
return true
}
// IsEnglishWithSpace 验证是否是英文字符(允许空格)
func IsEnglishWithSpace(str string) bool {
if strings.TrimSpace(str) == "" {
return false
}
for _, char := range str {
if unicode.IsSpace(char) {
continue
}
if !unicode.IsLetter(char) {
return false
}
if !isEnglishLetter(char) {
return false
}
}
return true
}
// IsAlphanumeric 验证是否是字母和数字组合
func IsAlphanumeric(str string) bool {
if strings.TrimSpace(str) == "" {
return false
}
for _, char := range str {
if !unicode.IsLetter(char) && !unicode.IsDigit(char) {
return false
}
}
return true
}
// IsStrongPassword 验证强密码至少8位包含大小写字母和数字
func IsStrongPassword(password string) bool {
if len(password) < 8 {
return false
}
var hasUpper, hasLower, hasDigit bool
for _, char := range password {
switch {
case unicode.IsUpper(char):
hasUpper = true
case unicode.IsLower(char):
hasLower = true
case unicode.IsDigit(char):
hasDigit = true
}
}
return hasUpper && hasLower && hasDigit
}
// 辅助函数:判断是否是英文字母
func isEnglishLetter(char rune) bool {
return (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z')
}

View File

@@ -3,25 +3,25 @@ package with
import (
"git.apinb.com/bsm-sdk/core/conf"
"git.apinb.com/bsm-sdk/core/database"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/types"
"git.apinb.com/bsm-sdk/core/vars"
"gorm.io/gorm"
)
func Databases(cfg *conf.DBConf, db *gorm.DB, opts *types.SqlOptions) {
func Databases(cfg *conf.DBConf, opts *types.SqlOptions) *gorm.DB {
if cfg == nil || len(cfg.Source) == 0 {
panic("No Database Source Found !")
}
// print inform.
print.Info("[BSM - %s] Databases: %v", vars.ServiceKey, cfg)
printer.Info("[BSM - %s] Databases: %v", vars.ServiceKey, cfg)
var err error
db, err = database.NewDatabase(cfg.Driver, cfg.Source, opts)
db, err := database.NewDatabase(cfg.Driver, cfg.Source, opts)
if err != nil {
print.Error("Database Init Failed !")
printer.Error("Database Init Failed !")
panic(err)
}
return
return db
}

View File

@@ -5,13 +5,13 @@ import (
"git.apinb.com/bsm-sdk/core/conf"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/vars"
"go.etcd.io/etcd/client/pkg/v3/transport"
clientv3 "go.etcd.io/etcd/client/v3"
)
func Etcd(cfg *conf.EtcdConf, cli *clientv3.Client) {
func Etcd(cfg *conf.EtcdConf) (cli *clientv3.Client) {
if cfg == nil || len(cfg.Endpoints) == 0 {
return
}
@@ -35,7 +35,7 @@ func Etcd(cfg *conf.EtcdConf, cli *clientv3.Client) {
}
tlsConfig, err := tlsInfo.ClientConfig()
if err != nil {
print.Error(errcode.ErrEtcd.Error())
printer.Error(errcode.ErrEtcd.Error())
panic(err)
}
etcdCfg.TLS = tlsConfig
@@ -44,11 +44,11 @@ func Etcd(cfg *conf.EtcdConf, cli *clientv3.Client) {
var err error
cli, err = clientv3.New(etcdCfg)
if err != nil {
print.Error(errcode.ErrEtcd.Error())
printer.Error(errcode.ErrEtcd.Error())
panic(err)
}
// print inform.
print.Info("[BSM - %s] Service Center: %v", vars.ServiceKey, cfg.Endpoints)
printer.Info("[BSM - %s] Service Center: %v", vars.ServiceKey, cfg.Endpoints)
return
}

View File

@@ -4,12 +4,12 @@ import (
"context"
"time"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/vars"
"github.com/allegro/bigcache/v3"
)
func Memory(cli *bigcache.BigCache, opts *bigcache.Config) {
func Memory(opts *bigcache.Config) (cli *bigcache.BigCache) {
if opts == nil {
opts = &bigcache.Config{
Shards: 1024,
@@ -27,9 +27,10 @@ func Memory(cli *bigcache.BigCache, opts *bigcache.Config) {
var err error
cli, err = bigcache.New(context.Background(), *opts)
if err != nil {
print.Error("Memory Cache Fatal Error")
printer.Error("Memory Cache Fatal Error")
panic(err)
}
print.Success("[BSM - %s] Memory Cache: Shards=%d, MaxEntrySize=%d", vars.ServiceKey, opts.Shards, opts.MaxEntrySize)
printer.Success("[BSM - %s] Memory Cache: Shards=%d, MaxEntrySize=%d", vars.ServiceKey, opts.Shards, opts.MaxEntrySize)
return
}

View File

@@ -2,15 +2,17 @@ package with
import (
"git.apinb.com/bsm-sdk/core/cache/redis"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/vars"
)
func RedisCache(cfg string, cli *redis.RedisClient) {
func RedisCache(cfg string) (cli *redis.RedisClient) {
if cfg != "" {
cli = redis.New(cfg, vars.ServiceKey)
// print inform.
print.Info("[BSM - %s] Cache: %s, DBIndex: %d", vars.ServiceKey, cfg, cli.DB)
printer.Info("[BSM - %s] Cache: %s, DBIndex: %d", vars.ServiceKey, cfg, cli.DB)
}
return
}