首页 > 数据库 >go语言使用单例模式封装数据库连接池

go语言使用单例模式封装数据库连接池

时间:2023-10-18 09:04:23浏览次数:47  
标签:err DB 数据库 db 单例 go gorm 连接池 Once

package singledb

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
)

// 数据库连接对象只有一个
var (
	db   *gorm.DB
	Once sync.Once //只执行一次某个操作的机制
)

func GetDbInstance() *gorm.DB {
	Once.Do(func() {
		var err error
		dsn := "root:root@tcp(127.0.0.1:8889)/shop"
		db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
		if err != nil {
			panic("数据库连接失败")
		}
	})
	return db
}

  

标签:err,DB,数据库,db,单例,go,gorm,连接池,Once
From: https://www.cnblogs.com/superzwb/p/17771213.html

相关文章

  • Go 提取字符串中url,转换为markdown格式并替换
     Go提取字符串中url,转换为markdown格式并替换//MakeContentUrlToMarkDown将字符串中url非markdown格式转[](url)格式funcMakeContentUrlToMarkDown(sourceStringstring)(resultStringstring){//urlReMustCompile:=regexp.MustCompile(".*(?P<URL>(http|https|......
  • 菜鸡go后端开发学习笔记1
        首先了解项目内容及对应的人员:重要的是产品以及前端。1、了解项目,理清逻辑,有什么不通顺的地方不清楚的地方及时的与产品进行沟通。2、在写请求时,主要是前端发送请求给到后端,后端通过逻辑处理获取数据库里面对应的数据,并返回数据。所以请求字段和前端是有交互......
  • Go - Making an HTTP Client Request
    Problem: YouwanttomakeanHTTPrequesttoawebserver.Solution: Usethenet/httppackagetomakeanHTTPrequest. HTTPisarequest-respondprotocol,andservingrequestsisonlyhalfofthestory.Theotherhalfismakingrequests.Thenet/http......
  • Go - Using Templates for Go Web Applications
    Problem: YouwanttouseGo’stemplatingsystemtocreateawebapplication.Solution: Usethehtml/templatepackagetocreateawebapplication. packagemainimport("html/template""net/http")funchello......
  • Go - Serving Through HTTPS
    Problem: YouwanttoserveyourwebapplicationthroughHTTPS.Solution: Usethehttp.ListenAndServeTLSfunctiontoserveyourwebapplicationthroughHTTPS. HTTPSisnothingmorethanlayeringHTTPontopoftheTransportSecurityLayer(TLS).Thenet......
  • redis介绍和安装、redis普通连接和连接池、redis字符串类型、redis hash类型、redis列
    redis介绍和安装#1redis什么-数据库就是个存数据的地方:只是不同数据库数据组织,存放形式不一样-mysql关系型数据库(oracle,sqlserver,postgrasql)-非关系型数据(nosql):redis,mongodb,clickhouse,infludb,elasticsearch,hadoop。。。-没有sql:没有sql语句......
  • 从内存使用角度的比较:Go vs Rust
    Go和Rust是最近几年非常火的语言,经常有人问到底该怎么选择,特别是谁更适合搭建网络后台服务,哪一个性能更好,稳定性更高。网络上Go和Rust的比较文章很多,大体上是做一个测试或写几段测试代码,根据运行的时长来比较哪个性能更好,但这种测试可能会陷入误区:1)比来比去,比的是网络IO,因为这种......
  • Go - Creating a JSON Web Service API
    Problem: YouwanttocreateasimplewebserviceAPIthatreturnsJSON.Solution: Usethenet/httppackagetocreateawebserviceAPIandtheencoding/jsonpackagetoencodedatatobesentbackasJSON. You’llcreateawebserviceAPIthatreturnsa......
  • RunnerGo UI自动化使用体验
    首先需要进入官网,RunnerGo支持开源,可以自行下载安装,也可以点击右上角体验企业版按钮快速体验点击体验企业版进入工作台后可以点击页面上方的UI自动化进入到测试页面创建元素我们可以在元素管理中创建我们测试时需要的元素这里我们以一个打开百度搜索的场景,添加了百度输入框和百度......
  • Go - Serving Static Files
    Problem: Youwanttoservestaticfilessuchasimages,CSS,andJavaScriptfiles.Solution: Usethehttp.FileServerfunctiontoservestaticfiles. funcmain(){dir:=http.Dir("./static")fs:=http.FileS......