22

Go 编程: 应用级抽象之信号管控

 4 years ago
source link: https://studygolang.com/articles/26741
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在软件开发过程中,我们常常做的一件事,就是编写公用库,或是基础库。这个过程可以称之为 应用级抽象 。应用级抽象的好处在于,接口主要面向应用,所以在适配度远远超过功能性接口。

以信号管控为例,在 Go 语言中管控进程信号,非常简单。只需要简单的 3 行代码即可完成管控:

package main

import "os/signal"

func main() {
    //信号接收 channel
    sigCh := make(chan os.Signal, 1)
    
    //监听信号(所有信号)
    signal.Notify(sigCh)

    //信号触发
    sig := <-sigch
    //TODO
}

但在实际开发过程中,这些功能性的函数缺少了 应用级抽象 ,想要像搭积木一样构建应用程序多少有些不便。所以,花了点时间做一下应用级别抽象,方便以后使用。

既然是应用级抽象,就从应用层面入手,首先给这块抽象的积木,按照功能命个名,就叫 Capture 好了。

//信号捕获器
type Capture struct{
  //TODO
}

既然是信号捕获, 在创建 Capture 时需要定义具体信号的触发操作,将具体 <信号,触发函数> ,取个英文名 Trap 。那么,在创建 Capture 时,就可以做为参数传进去。同时, Capture 必须处于服务状态,才可以监听并触发信号操作,所以需要提供一个 Capture.Serve 函数。最终希望的应用级接口就是这样:

package main

import (
    "context"
    "log"
    "syscall"

    "github.com/x-mod/sigtrap"
)

func main() {
  ctx, cancel := context.WithCancel(context.Background())
  
    capture := sigtrap.New(
        sigtrap.Trap(syscall.SIGINT, sigtrap.Handler(cancel)),
        sigtrap.Trap(syscall.SIGTERM, sigtrap.Handler(cancel)),
    )
    defer capture.Close()
    log.Println("sigtrap: waiting ...")
    log.Println("sigtrap:", capture.Serve(ctx))
}

具体的 Capture 实现也非常的简单,可以直接参考项目源码: github.com/x-mod/sigtrap .很多类似这样简单工具包均没有太多的技术难度,封装主要目的就是在做 应用级抽象

这个包主要用在我的另外一个应用级抽象包: x-mod/routine 中。它主要抽象的是, main 函数与 go routine 协程控制,具体实现功能以后抽时间分享,感兴趣的话可以参考项目源码。

更多 应用级抽象 工具包目录在这个仓库: github.com/x-mod/index .

基础库

网络库


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK