关于golang:数据库SQL-server数据实时同步到mysql2

golang代码实现

1. 目录构造

.
├── config  //配置文件
│   ├── config.go
│   ├── config_test.go
│   └── dev_custom.yml
├── dao // mysql数据库操作
│   ├── mysql.go // 初始化mysql
│   ├── record.go // 记录表操作
│   ├── record_test.go
│   ├── users.go 
│   └── users_test.go
├── go.mod
├── go.sum
├── logic // 业务逻辑
│   ├── logic.go
│   └── logic_test.go
├── main.go // 入口函数
├── models  // 数据库字段模型
│   ├── casbin_rule.go
│   ├── record.go
│   ├── reverse // xorm数据库主动生成表构造工具
│   │   ├── README.txt
│   │   ├── custom.yml
│   │   └── gennerate.sh // 可执行文件
│   ├── user.go
│   └── users.go
├── sqldao // sql server数据库操作
│   ├── connect_test.go 
│   ├── gorm_test.go
│   ├── sql.go // 初始化sql
│   ├── users.go // users表操作
│   └── users_test.go
└── sqlserver.exe

2.各个文件内容

2.1 dev_custom.yml

mySql:
  dns: "user:passwd@tcp(127.0.0.1:3306)/wzz_db?charset=utf8"

sqlServer:
  dns: "sqlserver://sa:123456@localhost:1433?database=wzz"

2.1 config.go

package config

import (
    "fmt"
    "github.com/mitchellh/mapstructure"
    "github.com/spf13/viper"
    "runtime"
    "strings"
)

// CustomT CustomT
type Mysql struct {
    DNS string `yaml:"dns"`
}

type SqlServer struct {
    DNS string `yaml:"dns"`
}

// CustomT CustomT
type CustomT struct {
    Mysql     Mysql     `yaml:"mySql"`
    SqlServer SqlServer `yaml:"sqlServer"`
}

// Custom Custom
var Custom CustomT

// ReadConfig ReadConfig for custom
func ReadConfig(configName string, configPath string, configType string) *viper.Viper {
    v := viper.New()
    v.SetConfigName(configName)
    v.AddConfigPath(configPath)
    v.SetConfigType(configType)
    err := v.ReadInConfig()
    if err != nil {
        return nil
    }
    return v
}

func CurrentFileDir() string {
    _, file, _, ok := runtime.Caller(1)
    if !ok {
        return "失败"
    }
    i := strings.LastIndex(file, "/")
    if i < 0 {
        i = strings.LastIndex(file, "\\")
    }

    return string(file[0 : i+1])
}

// InitConfig InitConfig
func InitConfig() {
    path := CurrentFileDir()
    v := ReadConfig("dev_custom", path, "yml")
    md := mapstructure.Metadata{}
    err := v.Unmarshal(&Custom, func(config *mapstructure.DecoderConfig) {
        config.TagName = "yaml"
        config.Metadata = &md
    })
    if err != nil {
        panic(err)
        return
    }
    fmt.Println("InitConfig Success!")
}

2.1 dev_custom.yml

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理