初始化
简介
- 本文提供一个完整的初始化实例,包含前文所涉及到的模块
- 示例代码摘取自 i3work 项目
main.go
package main
import (
"fmt"
"os"
"os/signal"
"strings"
"syscall"
_ "i3work/service" //导入services
_ "github.com/ie310mu/ie310go/cache/redis" //导入缓存的redis驱动
"github.com/ie310mu/ie310go/common/dir"
"github.com/ie310mu/ie310go/common/json"
"github.com/ie310mu/ie310go/common/logsagent"
_ "github.com/ie310mu/ie310go/session/redis" //导入session的redis驱动
"i3work/cache"
cu "i3work/config"
"github.com/ie310mu/ie310go"
"github.com/ie310mu/ie310go/route"
)
func main() {
//异常处理
defer func() {
if err := recover(); err != nil {
logsagent.Error("Exception has been caught. ", err)
logsagent.Warn("Press return to exit.")
var empty string
fmt.Scanln(&empty)
}
}()
//初始化应用程序
appinit()
//启动servers(在协程中启动,便于实现优雅退出)
go ie310go.Run(nil)
defer ie310go.Stop()
//实现优雅退出
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
for s := range sigs {
switch s {
case syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT:
logsagent.Info("got signal and try to exit: ", s)
return
default:
fmt.Println("got other signal : ", s)
}
}
}
func appinit() {
//配置初始化
configFileName := "appconfig.json"
logFileName := "logs/i3work.log"
for _, arg := range os.Args {
//fmt.Println("参数"+strconv.Itoa(idx)+":", arg)
if strings.Index(arg, "-cf ") == 0 { //配置文件
fileName := arg[4:]
fileName = strings.Trim(fileName, "")
configFileName = fileName
}
if strings.Index(arg, "-lf ") == 0 { //日志文件
fileName := arg[4:]
fileName = strings.Trim(fileName, "")
logFileName = fileName
}
}
cfg := cu.Init(configFileName)
//日志初始化 //先初始化日志,不然后面有的代码处日志无法输出
ie310go.AppLogsInitFunc = nil //取消默认日志初始方法
ie310go.InitLogs(`{"filename":"` + logFileName + `"}`)
logsagent.Info("configFile: " + configFileName)
logsagent.Info("logFile: " + logFileName)
//缓存初始化
cache.Init()
//数据库初始化
ie310go.SetDbInfo(cfg.DataBase, cfg.DataBaseRO)
//session初始化
//ie310go.SetDefaultSessionInfo("JSESSIONID", false)
//ie310go.AppSessionInitFunc = session.Init
ie310go.AppSessionInitFunc = nil //不使用session
//server初始化
httpConfig := route.ServerHTTPConfig{
Port: cfg.Port,
ServiceSuffix: cfg.ServiceSuffix,
Jsonp: true,
ServeStaticFunc: route.DefaultServeStatic,
DefaultStaticDir: dir.GetCurrentPath() + "static",
}
logsagent.Info("the DefaultServeStatic is " + httpConfig.DefaultStaticDir)
if cfg.StaticFilePath != "" && cfg.StaticFilePath != httpConfig.DefaultStaticDir {
httpConfig.DefaultStaticDir = cfg.StaticFilePath
logsagent.Info("reset the DefaultServeStatic to " + httpConfig.DefaultStaticDir)
}
srv := route.NewServerHTTP(httpConfig, "httpServer")
exportServices(route.Services, srv)
route.RegisterServer(srv)
}
func exportServices(ss []route.IService, srv route.Server) {
for _, s := range ss {
srv.RegisterService(s)
}
}
配置文件类
package config
import (
"github.com/ie310mu/ie310go/config"
)
// Config ...
var Config AppConfig
// Init ...
func Init(file string) AppConfig {
config.ScanFromFile(file, &Config)
return Config
}
//AppConfig ..
type AppConfig struct {
Port string
AdminPort string
ServiceSuffix string
Jsonp bool
LogArgs bool
Appkey string
StaticFilePath string
RiotIndexPath string
DataBase gosql.Config
DataBaseRO gosql.Config
RedisURL string
}
配置文件
{
"Port": "8083",
"AdminPort": "8084",
"ServiceSuffix": "goss",
"Jsonp": true,
"LogArgs": false,
"Appkey": "i3work_goservcie",
"RedisURL": "127.0.0.1:6379",
"StaticFilePath": "",
"RiotIndexPath": "",
"DataBase": {
"enable": true,
"driver": "mysql",
"dsn": "username:password@tcp(server:ip)/dbname?charset=utf8&parseTime=True&loc=Asia%2FShanghai",
"show_sql": true,
"max_open_conns": 20,
"max_idle_conns": 20,
"max_life_time": 3600
},
"DataBaseRO": {
"enable": true,
"driver": "mysql",
"dsn": "username:password@tcp(server:ip)/dbname?charset=utf8&parseTime=True&loc=Asia%2FShanghai",
"show_sql": true,
"max_open_conns": 20,
"max_idle_conns": 20,
"max_life_time": 3600
}
}
cache
package cache
import (
"i3work/config"
"fmt"
"github.com/ie310mu/ie310go/cache"
"github.com/ie310mu/ie310go/common/logsagent"
"github.com/ie310mu/ie310go/common/obj"
"github.com/ie310mu/ie310go/common/throw"
)
//Bm 根据配置确定是存储在memory还是redis
var Bm cache.Cache
//BmMemory 只存储在memory
var BmMemory cache.Cache
//GetString ..
func GetString(k string) string {
v := Bm.Get(k)
if obj.InterfaceIsNil(v) {
return ""
}
switch v.(type) {
case string:
return v.(string)
case []byte:
data := v.([]byte)
return string(data)
default:
return fmt.Sprint(v)
}
}
//Init ..
func Init() {
if config.Config.RedisURL != "" {
logsagent.Info("cache where init as redis : " + config.Config.RedisURL)
bm, err := cache.NewCache("redis", `{"conn":"`+config.Config.RedisURL+`"}`)
throw.CheckErr(err)
Bm = bm
logsagent.Info("cache init as redis : " + config.Config.RedisURL)
} else {
logsagent.Info("cache where init as memory ")
bm, err := cache.NewCache("memory", `{"interval":60}`)
throw.CheckErr(err)
Bm = bm
logsagent.Info("cache init as memory ")
}
{
bm, err := cache.NewCache("memory", `{"interval":60}`) //interval:多久检查一次过期,单位s
throw.CheckErr(err)
BmMemory = bm
}
}