微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

GIN试玩:GORM连接MYSQL,GIN连接REDIS

MysqL

安装依赖

go get "github.com/jinzhu/gorm"
go get "github.com/jinzhu/gorm/dialects/MysqL"

主体内容init函数中,main.go直接引入即可

// MysqL.go
package MysqL

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"go-service/src/Config"
	"strings"
)
import _ "github.com/jinzhu/gorm/dialects/MysqL"

var DB *gorm.DB

func init() {
	path := strings.Join([]string{Config.MysqL_URL.UserName, ":", Config.MysqL_URL.Password, "@tcp(", Config.MysqL_URL.Ip, ":", Config.MysqL_URL.Port, ")/", Config.MysqL_URL.DataBase, "?charset=utf8"}, "")
	var err error
	DB, err = gorm.Open("MysqL", path)
	if err != nil {
		DB.Close()
		fmt.Println(err.Error())
	}
	fmt.Println("已连接")
	// 设置连接池,空闲连接
	DB.DB().SetMaxIdleConns(50)
	// 打开链接
	DB.DB().SetMaxOpenConns(100)

	// 表明禁用后缀加s
	DB.SingularTable(true)
}

Re@R_404_6422@

安装依赖

go get "github.com/go-re@R_404_6422@/re@R_404_6422@/v8"

MysqL同步

// re@R_404[email protected]
package Re@R_404_6422@

import (
	"context"
	"fmt"
	"github.com/go-re@R_404_6422@/re@R_404_6422@/v8"
	"go-service/src/Config"
	"time"
)

var (
	Re@R_404_6422@ *re@R_404[email protected]
)

var ctx = context.Background()

func init() {
	Re@R_404_6422@ = re@R_404[email protected](&re@R_404[email protected]{
		Addr:     Config.RE@R_404_6422@_URL.Ip + ":" + Config.RE@R_404_6422@_URL.Port,
		Password: "", // no password set
		DB:       0,  // use default DB
	})
}

func SetRe@R_404_6422@(key string, value string, t int) bool {
	expire := time.Duration(t) * time.Second
	if err := Re@R_404[email protected](ctx, key, value, expire).Err(); err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

func GetRe@R_404_6422@(key string) string {
	result, err := Re@R_404[email protected](ctx, key).Result()
	if err != nil {
		fmt.Println(err)
		return ""
	}
	return result
}

func DelRe@R_404_6422@(key string) bool {
	_, err := Re@R_404[email protected](ctx, key).Result()
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}
// 延长过期时间
func ExpireRe@R_404_6422@(key string, t int) bool {
	expire := time.Duration(t) * time.Second
	if err := Re@R_404[email protected](ctx, key, expire).Err(); err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

运行

package main

import (
	_ "go-service/src/MysqL"
	_ "go-service/src/Re@R_404_6422@"
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐