go语言封装的 mysql 和 封装的 redis

package main

import (
	"fmt"
	"os"
	"sync"

	_ "github.com/go-sql-driver/mysql"
	//	数据库依赖
	"github.com/garyburd/redigo/redis"
	"github.com/jmoiron/sqlx"
)

var (
	//	数据库读写锁
	dbMt      sync.RWMutex
	mysqlDB        *sqlx.DB
	redisPool *redis.Pool
)

func InitMysql(){
	if mysqlDB == nil {
		db, err := sqlx.Connect("mysql", "root:123456@tcp(12.12.12.12:3306)/thinkphp")
		mysqlDB = db
		HandleError(err,`sqlx.Connect("mysql","root:123456@tcp(12.12.12.12:3306)/thinkphp")`)
	}
}

func CloseMysql(){
	if mysqlDB != nil {
		mysqlDB.Close()
	}
}

func GetRedisConn() redis.Conn{
	if redisPool == nil{
		redisPool = &redis.Pool{
			MaxActive:   100,
			MaxIdle:     10,
			IdleTimeout: 10,
			Dial: func() (redis.Conn, error) {
				conn, err := redis.Dial("tcp", "12.12.12.12:6379")
				HandleError(err,`redis.Dial("tcp", "12.12.12.12:6379")`)
				//redis密码
				_, e := conn.Do("AUTH", "123456")
				HandleError(e,`conn.Do("AUTH", "123456")`)
				//指定redis哪个库
				_, err = conn.Do("select", "1")
				HandleError(err,`conn.Do("select", "1")`)
				return conn, err
			}}
	}
	return redisPool.Get()
}

func CloseRedis(){
	if redisPool != nil {
		redisPool.Close()
	}
}

func WriteRedis(name string,score int){
//调用redis
	conn := GetRedisConn()
	_, err := conn.Do("set", name, score)
	HandleError(err,"conn.Do set")
}

func ReadRedis(name string) (score int,err error) {
//调用redis
	conn := GetRedisConn()
	reply, err := conn.Do("get", name)
	HandleError(err,"conn.Do get")
	score, err = redis.Int(reply, err)
	return score, err
}

func ReadMysql(name string){
	dbMt.RLock()
//调用mysql
	InitMysql()
	results := make([]ExamResult, 0)
	err := mysqlDB.Select(&results, "select * from score where name=?;", name)
	HandleError(err,"mysqlDB.Select")
	fmt.Println(results)
	dbMt.RUnlock()

	//	写入redis
	WriteRedis(name,results[0].Score)
}

func WriteMysql(scoreMap map[string]int){
	dbMt.Lock()
//调用mysql
	InitMysql()
	for name,score := range scoreMap{
		_, err := mysqlDB.Exec("insert into score(name,score) values(?,?);", name, score)
		if err != nil {
			fmt.Println("插入失败err=",err)
			os.Exit(1)
		}
	}
	dbMt.Unlock()
}

 

你可能感兴趣的:(go语言)