2021-01-17 21:46:25 +08:00
|
|
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
2018-05-10 16:07:14 +08:00
|
|
|
//
|
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2018-05-19 01:04:20 +08:00
|
|
|
|
2018-05-10 16:07:14 +08:00
|
|
|
package gproc
|
|
|
|
|
|
|
|
|
|
import (
|
2021-09-01 15:02:58 +08:00
|
|
|
"context"
|
2019-12-11 21:22:41 +08:00
|
|
|
"fmt"
|
2022-02-16 20:51:39 +08:00
|
|
|
"sync"
|
2021-11-15 20:49:02 +08:00
|
|
|
|
2021-10-11 21:41:56 +08:00
|
|
|
"github.com/gogf/gf/v2/container/gmap"
|
feat(instance): migrate instance containers to type-safe generics (#4617)
### 变更说明
本次重构将项目中用于**实例管理的容器**从 `StrAnyMap`/`IntAnyMap` 迁移到类型安全的泛型实现
`KVMapWithChecker`,同时将相关的 `glist.List` 和 `gqueue.Queue`
替换为对应的泛型版本,以提高实例管理的类型安全性。并且减少原先代码中的大量类型断言,提高性能。
### 前因
目前`goframe`中大量使用了包含`any`的容器,然后通过断言去转换类型,麻烦且影响性能,尤其是对`gdb/gredis/glog`等需要高频获取`instance`实例的组件影响较大。最近几个版本中gf完成了数据结构容器的泛型化改造,以及我最近解决了其中几个泛型容器对于`typed
nil`过滤的问题,所以可以逐步迁移这些实例容器到泛型容器,减少断言优化性能
### 主要改进
#### 1. 实例容器泛型化
以下模块的实例管理容器已迁移到泛型实现:
**核心实例管理**:
- `database/gdb`: 数据库实例容器 → `KVMap[string, DB]`
- `database/gredis`: Redis 实例容器 → `KVMap[string, *Redis]`
- `database/gredis`: Redis 配置容器 → `KVMap[string, *Config]`
- `os/gcfg`: 配置实例容器 → `KVMap[string, *Config]`
- `os/glog`: 日志实例容器 → `KVMap[string, *Logger]`
- `os/gview`: 视图实例容器 → `KVMap[string, *View]`
- `i18n/gi18n`: 国际化实例容器 → `KVMap[string, *Manager]`
**网络服务实例**:
- `net/ghttp`: HTTP 服务器容器 → `KVMap[string, *Server]`
- `net/gtcp`: TCP 服务器容器 → `KVMap[any, *Server]`
- `net/gudp`: UDP 服务器容器 → `KVMap[string, *Server]`
**其他实例容器**:
- `os/gres`: 资源实例容器 → `KVMap[string, *Resource]`
- `os/gfpool`: 文件池容器 → `KVMap[string, *Pool]`
- `os/gspath`: 路径搜索容器 → `KVMap[string, *SPath]`
- `net/gtcp`: 连接池容器 → `KVMap[string, *gpool.Pool]`
#### 2. 相关数据结构泛型化
- `os/gfsnotify`: 回调列表 → `TList[*Callback]`,事件队列 → `TQueue[*Event]`
- `os/grpool`: 任务队列 → `TList[*localPoolItem]`
- `os/gcache`: 事件队列 → `TList[*adapterMemoryEvent]`
- `net/ghttp`: 解析项列表 → `TList[*HandlerItemParsed]`
- `os/gproc`: 消息队列 → `TQueue[*MsgRequest]`
- `os/gmlock`: 锁映射 → `KVMap[string, *sync.RWMutex]`
### 技术实现
1. **引入检查器函数**: 为每个实例容器添加 `checker` 函数用于空值检测
2. **消除类型断言**: 实例获取时无需 `v.(*Type)` 转换
3. **明确函数签名**: `GetOrSetFuncLock` 的回调从 `func() any` 改为 `func() T`
### 使用示例
#### 实例容器的变更
**变更前**:
```go
// 旧的实例管理方式
var instances = gmap.NewStrAnyMap(true)
func Instance(name string) *Logger {
v := instances.GetOrSetFuncLock(name, func() any {
return New()
})
return v.(*Logger) // 需要类型断言
}
```
**变更后**:
```go
// 新的泛型实例容器
var (
checker = func(v *Logger) bool { return v == nil }
instances = gmap.NewKVMapWithChecker[string, *Logger](checker, true)
)
func Instance(name string) *Logger {
return instances.GetOrSetFuncLock(name, New) // 直接返回,无需断言
}
```
#### 队列容器的变更
**变更前**:
```go
// 旧的队列方式
events := gqueue.New()
events.Push(&Event{Path: "/tmp/file"})
if v := events.Pop(); v != nil {
event := v.(*Event) // 需要类型断言
handleEvent(event)
}
```
**变更后**:
```go
// 新的泛型队列
events := gqueue.NewTQueue[*Event]()
events.Push(&Event{Path: "/tmp/file"})
if event := events.Pop(); event != nil {
handleEvent(event) // event 已是 *Event 类型
}
```
### 收益
- ✅ **编译时类型安全**: 实例容器的类型错误在编译期捕获
- ✅ **消除运行时断言**: 避免类型断言带来的 panic 风险
- ✅ **提升代码可读性**: 实例管理逻辑更清晰
- ✅ **改善开发体验**: IDE 类型提示和代码补全更准确
### 性能权衡
**编译时**:
- 泛型实例化会增加编译时间和二进制体积
- 预估编译时间增加 5-15%,二进制体积增加约 1-2MB
**运行时**:
- 减少类型断言的反射开销
- 提升实例获取等热点路径的性能
2026-01-16 15:23:13 +08:00
|
|
|
"github.com/gogf/gf/v2/container/gqueue"
|
2021-10-11 21:41:56 +08:00
|
|
|
"github.com/gogf/gf/v2/errors/gerror"
|
|
|
|
|
"github.com/gogf/gf/v2/internal/intlog"
|
|
|
|
|
"github.com/gogf/gf/v2/net/gtcp"
|
|
|
|
|
"github.com/gogf/gf/v2/os/gfile"
|
|
|
|
|
"github.com/gogf/gf/v2/util/gconv"
|
2018-05-10 16:07:14 +08:00
|
|
|
)
|
|
|
|
|
|
2019-12-11 21:22:41 +08:00
|
|
|
// MsgRequest is the request structure for process communication.
|
|
|
|
|
type MsgRequest struct {
|
2022-02-16 20:51:39 +08:00
|
|
|
SenderPid int // Sender PID.
|
|
|
|
|
ReceiverPid int // Receiver PID.
|
|
|
|
|
Group string // Message group name.
|
|
|
|
|
Data []byte // Request data.
|
2019-06-15 21:41:20 +08:00
|
|
|
}
|
|
|
|
|
|
2019-12-11 21:22:41 +08:00
|
|
|
// MsgResponse is the response structure for process communication.
|
|
|
|
|
type MsgResponse struct {
|
|
|
|
|
Code int // 1: OK; Other: Error.
|
|
|
|
|
Message string // Response message.
|
|
|
|
|
Data []byte // Response data.
|
|
|
|
|
}
|
2018-07-04 19:32:51 +08:00
|
|
|
|
2019-12-11 21:22:41 +08:00
|
|
|
const (
|
2021-09-01 15:02:58 +08:00
|
|
|
defaultFolderNameForProcComm = "gf_pid_port_mapping" // Default folder name for storing pid to port mapping files.
|
|
|
|
|
defaultGroupNameForProcComm = "" // Default group name.
|
|
|
|
|
defaultTcpPortForProcComm = 10000 // Starting port number for receiver listening.
|
|
|
|
|
maxLengthForProcMsgQueue = 10000 // Max size for each message queue of the group.
|
2019-12-11 21:22:41 +08:00
|
|
|
)
|
2018-05-10 16:07:14 +08:00
|
|
|
|
2019-12-11 21:22:41 +08:00
|
|
|
var (
|
feat(instance): migrate instance containers to type-safe generics (#4617)
### 变更说明
本次重构将项目中用于**实例管理的容器**从 `StrAnyMap`/`IntAnyMap` 迁移到类型安全的泛型实现
`KVMapWithChecker`,同时将相关的 `glist.List` 和 `gqueue.Queue`
替换为对应的泛型版本,以提高实例管理的类型安全性。并且减少原先代码中的大量类型断言,提高性能。
### 前因
目前`goframe`中大量使用了包含`any`的容器,然后通过断言去转换类型,麻烦且影响性能,尤其是对`gdb/gredis/glog`等需要高频获取`instance`实例的组件影响较大。最近几个版本中gf完成了数据结构容器的泛型化改造,以及我最近解决了其中几个泛型容器对于`typed
nil`过滤的问题,所以可以逐步迁移这些实例容器到泛型容器,减少断言优化性能
### 主要改进
#### 1. 实例容器泛型化
以下模块的实例管理容器已迁移到泛型实现:
**核心实例管理**:
- `database/gdb`: 数据库实例容器 → `KVMap[string, DB]`
- `database/gredis`: Redis 实例容器 → `KVMap[string, *Redis]`
- `database/gredis`: Redis 配置容器 → `KVMap[string, *Config]`
- `os/gcfg`: 配置实例容器 → `KVMap[string, *Config]`
- `os/glog`: 日志实例容器 → `KVMap[string, *Logger]`
- `os/gview`: 视图实例容器 → `KVMap[string, *View]`
- `i18n/gi18n`: 国际化实例容器 → `KVMap[string, *Manager]`
**网络服务实例**:
- `net/ghttp`: HTTP 服务器容器 → `KVMap[string, *Server]`
- `net/gtcp`: TCP 服务器容器 → `KVMap[any, *Server]`
- `net/gudp`: UDP 服务器容器 → `KVMap[string, *Server]`
**其他实例容器**:
- `os/gres`: 资源实例容器 → `KVMap[string, *Resource]`
- `os/gfpool`: 文件池容器 → `KVMap[string, *Pool]`
- `os/gspath`: 路径搜索容器 → `KVMap[string, *SPath]`
- `net/gtcp`: 连接池容器 → `KVMap[string, *gpool.Pool]`
#### 2. 相关数据结构泛型化
- `os/gfsnotify`: 回调列表 → `TList[*Callback]`,事件队列 → `TQueue[*Event]`
- `os/grpool`: 任务队列 → `TList[*localPoolItem]`
- `os/gcache`: 事件队列 → `TList[*adapterMemoryEvent]`
- `net/ghttp`: 解析项列表 → `TList[*HandlerItemParsed]`
- `os/gproc`: 消息队列 → `TQueue[*MsgRequest]`
- `os/gmlock`: 锁映射 → `KVMap[string, *sync.RWMutex]`
### 技术实现
1. **引入检查器函数**: 为每个实例容器添加 `checker` 函数用于空值检测
2. **消除类型断言**: 实例获取时无需 `v.(*Type)` 转换
3. **明确函数签名**: `GetOrSetFuncLock` 的回调从 `func() any` 改为 `func() T`
### 使用示例
#### 实例容器的变更
**变更前**:
```go
// 旧的实例管理方式
var instances = gmap.NewStrAnyMap(true)
func Instance(name string) *Logger {
v := instances.GetOrSetFuncLock(name, func() any {
return New()
})
return v.(*Logger) // 需要类型断言
}
```
**变更后**:
```go
// 新的泛型实例容器
var (
checker = func(v *Logger) bool { return v == nil }
instances = gmap.NewKVMapWithChecker[string, *Logger](checker, true)
)
func Instance(name string) *Logger {
return instances.GetOrSetFuncLock(name, New) // 直接返回,无需断言
}
```
#### 队列容器的变更
**变更前**:
```go
// 旧的队列方式
events := gqueue.New()
events.Push(&Event{Path: "/tmp/file"})
if v := events.Pop(); v != nil {
event := v.(*Event) // 需要类型断言
handleEvent(event)
}
```
**变更后**:
```go
// 新的泛型队列
events := gqueue.NewTQueue[*Event]()
events.Push(&Event{Path: "/tmp/file"})
if event := events.Pop(); event != nil {
handleEvent(event) // event 已是 *Event 类型
}
```
### 收益
- ✅ **编译时类型安全**: 实例容器的类型错误在编译期捕获
- ✅ **消除运行时断言**: 避免类型断言带来的 panic 风险
- ✅ **提升代码可读性**: 实例管理逻辑更清晰
- ✅ **改善开发体验**: IDE 类型提示和代码补全更准确
### 性能权衡
**编译时**:
- 泛型实例化会增加编译时间和二进制体积
- 预估编译时间增加 5-15%,二进制体积增加约 1-2MB
**运行时**:
- 减少类型断言的反射开销
- 提升实例获取等热点路径的性能
2026-01-16 15:23:13 +08:00
|
|
|
// checker is used for checking whether the value is nil.
|
|
|
|
|
checker = func(v *gqueue.TQueue[*MsgRequest]) bool { return v == nil }
|
2019-12-11 21:22:41 +08:00
|
|
|
// commReceiveQueues is the group name to queue map for storing received data.
|
feat(instance): migrate instance containers to type-safe generics (#4617)
### 变更说明
本次重构将项目中用于**实例管理的容器**从 `StrAnyMap`/`IntAnyMap` 迁移到类型安全的泛型实现
`KVMapWithChecker`,同时将相关的 `glist.List` 和 `gqueue.Queue`
替换为对应的泛型版本,以提高实例管理的类型安全性。并且减少原先代码中的大量类型断言,提高性能。
### 前因
目前`goframe`中大量使用了包含`any`的容器,然后通过断言去转换类型,麻烦且影响性能,尤其是对`gdb/gredis/glog`等需要高频获取`instance`实例的组件影响较大。最近几个版本中gf完成了数据结构容器的泛型化改造,以及我最近解决了其中几个泛型容器对于`typed
nil`过滤的问题,所以可以逐步迁移这些实例容器到泛型容器,减少断言优化性能
### 主要改进
#### 1. 实例容器泛型化
以下模块的实例管理容器已迁移到泛型实现:
**核心实例管理**:
- `database/gdb`: 数据库实例容器 → `KVMap[string, DB]`
- `database/gredis`: Redis 实例容器 → `KVMap[string, *Redis]`
- `database/gredis`: Redis 配置容器 → `KVMap[string, *Config]`
- `os/gcfg`: 配置实例容器 → `KVMap[string, *Config]`
- `os/glog`: 日志实例容器 → `KVMap[string, *Logger]`
- `os/gview`: 视图实例容器 → `KVMap[string, *View]`
- `i18n/gi18n`: 国际化实例容器 → `KVMap[string, *Manager]`
**网络服务实例**:
- `net/ghttp`: HTTP 服务器容器 → `KVMap[string, *Server]`
- `net/gtcp`: TCP 服务器容器 → `KVMap[any, *Server]`
- `net/gudp`: UDP 服务器容器 → `KVMap[string, *Server]`
**其他实例容器**:
- `os/gres`: 资源实例容器 → `KVMap[string, *Resource]`
- `os/gfpool`: 文件池容器 → `KVMap[string, *Pool]`
- `os/gspath`: 路径搜索容器 → `KVMap[string, *SPath]`
- `net/gtcp`: 连接池容器 → `KVMap[string, *gpool.Pool]`
#### 2. 相关数据结构泛型化
- `os/gfsnotify`: 回调列表 → `TList[*Callback]`,事件队列 → `TQueue[*Event]`
- `os/grpool`: 任务队列 → `TList[*localPoolItem]`
- `os/gcache`: 事件队列 → `TList[*adapterMemoryEvent]`
- `net/ghttp`: 解析项列表 → `TList[*HandlerItemParsed]`
- `os/gproc`: 消息队列 → `TQueue[*MsgRequest]`
- `os/gmlock`: 锁映射 → `KVMap[string, *sync.RWMutex]`
### 技术实现
1. **引入检查器函数**: 为每个实例容器添加 `checker` 函数用于空值检测
2. **消除类型断言**: 实例获取时无需 `v.(*Type)` 转换
3. **明确函数签名**: `GetOrSetFuncLock` 的回调从 `func() any` 改为 `func() T`
### 使用示例
#### 实例容器的变更
**变更前**:
```go
// 旧的实例管理方式
var instances = gmap.NewStrAnyMap(true)
func Instance(name string) *Logger {
v := instances.GetOrSetFuncLock(name, func() any {
return New()
})
return v.(*Logger) // 需要类型断言
}
```
**变更后**:
```go
// 新的泛型实例容器
var (
checker = func(v *Logger) bool { return v == nil }
instances = gmap.NewKVMapWithChecker[string, *Logger](checker, true)
)
func Instance(name string) *Logger {
return instances.GetOrSetFuncLock(name, New) // 直接返回,无需断言
}
```
#### 队列容器的变更
**变更前**:
```go
// 旧的队列方式
events := gqueue.New()
events.Push(&Event{Path: "/tmp/file"})
if v := events.Pop(); v != nil {
event := v.(*Event) // 需要类型断言
handleEvent(event)
}
```
**变更后**:
```go
// 新的泛型队列
events := gqueue.NewTQueue[*Event]()
events.Push(&Event{Path: "/tmp/file"})
if event := events.Pop(); event != nil {
handleEvent(event) // event 已是 *Event 类型
}
```
### 收益
- ✅ **编译时类型安全**: 实例容器的类型错误在编译期捕获
- ✅ **消除运行时断言**: 避免类型断言带来的 panic 风险
- ✅ **提升代码可读性**: 实例管理逻辑更清晰
- ✅ **改善开发体验**: IDE 类型提示和代码补全更准确
### 性能权衡
**编译时**:
- 泛型实例化会增加编译时间和二进制体积
- 预估编译时间增加 5-15%,二进制体积增加约 1-2MB
**运行时**:
- 减少类型断言的反射开销
- 提升实例获取等热点路径的性能
2026-01-16 15:23:13 +08:00
|
|
|
// The value of the map is type of *gqueue.TQueue[*MsgRequest].
|
|
|
|
|
commReceiveQueues = gmap.NewKVMapWithChecker[string, *gqueue.TQueue[*MsgRequest]](checker, true)
|
2019-12-11 21:22:41 +08:00
|
|
|
|
|
|
|
|
// commPidFolderPath specifies the folder path storing pid to port mapping files.
|
2021-09-01 15:02:58 +08:00
|
|
|
commPidFolderPath string
|
2019-12-11 21:22:41 +08:00
|
|
|
|
2022-02-16 20:51:39 +08:00
|
|
|
// commPidFolderPathOnce is used for lazy calculation for `commPidFolderPath` is necessary.
|
|
|
|
|
commPidFolderPathOnce sync.Once
|
|
|
|
|
)
|
2018-05-15 18:34:00 +08:00
|
|
|
|
2019-12-11 21:22:41 +08:00
|
|
|
// getConnByPid creates and returns a TCP connection for specified pid.
|
2019-12-13 17:40:29 +08:00
|
|
|
func getConnByPid(pid int) (*gtcp.PoolConn, error) {
|
2019-12-11 21:22:41 +08:00
|
|
|
port := getPortByPid(pid)
|
|
|
|
|
if port > 0 {
|
2019-12-13 17:40:29 +08:00
|
|
|
if conn, err := gtcp.NewPoolConn(fmt.Sprintf("127.0.0.1:%d", port)); err == nil {
|
2019-12-11 21:22:41 +08:00
|
|
|
return conn, nil
|
|
|
|
|
} else {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
2021-12-23 00:09:00 +08:00
|
|
|
return nil, gerror.Newf(`could not find port for pid "%d"`, pid)
|
2019-12-11 21:22:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// getPortByPid returns the listening port for specified pid.
|
|
|
|
|
// It returns 0 if no port found for the specified pid.
|
|
|
|
|
func getPortByPid(pid int) int {
|
2022-02-16 20:51:39 +08:00
|
|
|
path := getCommFilePath(pid)
|
|
|
|
|
if path == "" {
|
|
|
|
|
return 0
|
|
|
|
|
}
|
|
|
|
|
return gconv.Int(gfile.GetContentsWithCache(path))
|
2019-12-11 21:22:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// getCommFilePath returns the pid to port mapping file path for given pid.
|
|
|
|
|
func getCommFilePath(pid int) string {
|
2022-02-16 20:51:39 +08:00
|
|
|
path, err := getCommPidFolderPath()
|
|
|
|
|
if err != nil {
|
|
|
|
|
intlog.Errorf(context.TODO(), `%+v`, err)
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
return gfile.Join(path, gconv.String(pid))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// getCommPidFolderPath retrieves and returns the available directory for storing pid mapping files.
|
|
|
|
|
func getCommPidFolderPath() (folderPath string, err error) {
|
|
|
|
|
commPidFolderPathOnce.Do(func() {
|
|
|
|
|
availablePaths := []string{
|
|
|
|
|
"/var/tmp",
|
|
|
|
|
"/var/run",
|
|
|
|
|
}
|
|
|
|
|
if path, _ := gfile.Home(".config"); path != "" {
|
|
|
|
|
availablePaths = append(availablePaths, path)
|
|
|
|
|
}
|
|
|
|
|
availablePaths = append(availablePaths, gfile.Temp())
|
|
|
|
|
for _, availablePath := range availablePaths {
|
|
|
|
|
checkPath := gfile.Join(availablePath, defaultFolderNameForProcComm)
|
|
|
|
|
if !gfile.Exists(checkPath) && gfile.Mkdir(checkPath) != nil {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if gfile.IsWritable(checkPath) {
|
|
|
|
|
commPidFolderPath = checkPath
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
2022-03-07 09:57:51 +08:00
|
|
|
if commPidFolderPath == "" {
|
|
|
|
|
err = gerror.Newf(
|
|
|
|
|
`cannot find available folder for storing pid to port mapping files in paths: %+v`,
|
|
|
|
|
availablePaths,
|
|
|
|
|
)
|
|
|
|
|
}
|
2022-02-16 20:51:39 +08:00
|
|
|
})
|
|
|
|
|
folderPath = commPidFolderPath
|
|
|
|
|
return
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|