标签:ali elm port case har val 为知笔记 def reg
DBHelper, err = gorm.Open("mysql", "root:root@(115.159.59.129:3306)/test?charset=utf8&parseTime=True&loc=Local")
if err != nil {
log.Fatal("数据库初始化错误", err) //log.Fatal输出日志并且退出主程序
return
}
package src
import (
"context"
"log"
"os"
"os/signal"
"time"
)
var ServerSigChan chan os.Signal
var ctx context.Context
func init() {
ServerSigChan = make(chan os.Signal)
ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
go ServerNotify(ctx)
}
func ServerNotify(ctx context.Context) {
signal.Notify(ServerSigChan)
select {
case <-ServerSigChan:
ServerSigChan <- os.Interrupt
case <-ctx.Done(): //这里等待的时间可以用来在关闭连接的时候释放资源
ServerSigChan <- os.Interrupt
}
}
func ShutDownServer(err error) {
log.Println(err)
ServerSigChan <- os.Interrupt
log.Println("数据库优雅退出")
os.Exit(1)
}
package src
import (
"github.com/jinzhu/gorm"
"time"
)
var DBHelper *gorm.DB
var err error
func InitDB() {
DBHelper, err = gorm.Open("mysql", "root:root@(115.159.59.129:3306)/test?charset=utf8&parseTime=True&loc=Local")
if err != nil {
ShutDownServer(err) //关闭连接
}
DBHelper.SingularTable(true)
DBHelper.DB().SetMaxIdleConns(10)
DBHelper.DB().SetMaxOpenConns(100)
DBHelper.DB().SetConnMaxLifetime(time.Hour)
}
启动项目
func main(){
router := gin.Default()
go InitDB() //协程初始化数据库连接
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("topicurl", TopicUrl)
}
v1 := router.Group("/v2/mtopics")
{
v2.DELETE("/mtopics", DelMTopic)
}
router.Run()
}
标签:ali elm port case har val 为知笔记 def reg
原文地址:https://www.cnblogs.com/hualou/p/12071042.html