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

10次阅读

共计 1828 个字符,预计需要花费 5 分钟才能阅读完成。

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

正文完
 0