Commit 5ee28309 by mushishixian

添加redis操作模块

parent ae0e7551
package Boot
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
//mysql相关
var mysql_db *gorm.DB
func init(){
InitMysql()
}
func InitMysql() error {
var err error
mysql_db, err = gorm.Open("mysql", "root:root@tcp(192.168.2.239:3306)/test?charset=utf8&parseTime=True&loc=Local")
if err != nil {
mysql_db=nil
return NewFatalError(err.Error()) //这里返回致命异常
}
mysql_db.SingularTable(true)
mysql_db.DB().SetMaxIdleConns( 10)
mysql_db.DB().SetMaxOpenConns( 100)
mysql_db.LogMode(true)
return nil
}
func GetDB() *gorm.DB {
return mysql_db
}
\ No newline at end of file
...@@ -2,25 +2,25 @@ package Mapper ...@@ -2,25 +2,25 @@ package Mapper
import ( import (
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"jtthink/Boot" "jtthink/boot"
"jtthink/Vars" "jtthink/Vars"
) )
func GetCourseList() *gorm.DB { func GetCourseList() *gorm.DB {
return Boot.GetDB().Table(Vars.Table_CourseMain). return boot.GetDB().Table(Vars.Table_CourseMain).
Order("course_id desc").Limit(3) Order("course_id desc").Limit(3)
} }
const course_list="select * from course_main order by course_id desc limit ?" const course_list="select * from course_main order by course_id desc limit ?"
func GetCourseListBySql(args ...interface{}) *gorm.DB{ func GetCourseListBySql(args ...interface{}) *gorm.DB{
return Boot.GetDB().Raw(course_list,args...) return boot.GetDB().Raw(course_list,args...)
} }
func GetCourseDetail(course_id int ) *gorm.DB{ func GetCourseDetail(course_id int ) *gorm.DB{
return Boot.GetDB().Table(Vars.Table_CourseMain).Where("course_id=?",course_id) return boot.GetDB().Table(Vars.Table_CourseMain).Where("course_id=?",course_id)
} }
//取计数表 //取计数表
func GetCourseCounts(course_id int ) *gorm.DB{ func GetCourseCounts(course_id int ) *gorm.DB{
return Boot.GetDB().Table(Vars.Table_CourseCounts).Where("course_id=?",course_id) return boot.GetDB().Table(Vars.Table_CourseCounts).Where("course_id=?",course_id)
} }
package boot
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"jtthink/pkg/config"
)
//mysql相关
var mysqlDb *gorm.DB
func InitMysql() error {
var err error
userName := config.Get("database.user_name").String()
password := config.Get("database.password").String()
host := config.Get("database.host").String()
database := config.Get("database.database").String()
mysqlDb, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8&parseTime=True&loc=Local",
userName, password, host, database))
if err != nil {
mysqlDb = nil
return NewFatalError(err.Error()) //这里返回致命异常
}
mysqlDb.SingularTable(true)
mysqlDb.DB().SetMaxIdleConns(10)
mysqlDb.DB().SetMaxOpenConns(100)
mysqlDb.LogMode(true)
return nil
}
func GetDB() *gorm.DB {
return mysqlDb
}
package Boot package boot
type FatalError struct { type FatalError struct {
ErrMsg string ErrMsg string
......
package boot
import (
"jtthink/pkg/config"
"jtthink/pkg/mysql"
)
func Boot() (err error) {
if err = config.SetUp(); err != nil {
return
}
if err = mysql.Setup(); err != nil {
return
}
return
}
...@@ -3,25 +3,31 @@ package main ...@@ -3,25 +3,31 @@ package main
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/micro/go-micro/v2/web" "github.com/micro/go-micro/v2/web"
"jtthink/boot"
"jtthink/framework/gin_" "jtthink/framework/gin_"
_ "jtthink/lib" _ "jtthink/lib"
"log" "log"
) )
func main() { func main() {
r:=gin.New() if err := boot.Boot(); err != nil {
log.Println(err)
}
r := gin.New()
gin_.BootStrap(r) gin_.BootStrap(r)
//web改成micro 就是grpc,并直接注册到etcd里面 //web改成micro 就是grpc,并直接注册到etcd里面
service:=web.NewService( service := web.NewService(
web.Name("go.micro.api.http.course"), web.Name("go.micro.api.http.course"),
web.Handler(r), web.Handler(r),
) )
if err := service.Init(); err != nil {
service.Init() log.Println(err)
if err:= service.Run(); err != nil { }
if err := service.Run(); err != nil {
log.Println(err) log.Println(err)
} }
} }
\ No newline at end of file
...@@ -5,3 +5,8 @@ host = 192.168.2.239 ...@@ -5,3 +5,8 @@ host = 192.168.2.239
database = test database = test
table_prefix = table_prefix =
type = mysql type = mysql
[redis]
max_idle = 10
max_active = 10
idle_timeout = 20
\ No newline at end of file
...@@ -3,22 +3,23 @@ module jtthink ...@@ -3,22 +3,23 @@ module jtthink
go 1.14 go 1.14
require ( require (
github.com/favadi/protoc-go-inject-tag v1.0.0 // indirect
github.com/gin-gonic/gin v1.6.3 github.com/gin-gonic/gin v1.6.3
github.com/go-ini/ini v1.44.0 github.com/go-ini/ini v1.44.0
github.com/golang/protobuf v1.4.2 github.com/golang/protobuf v1.4.2
github.com/gomodule/redigo v2.0.1-0.20180401191855-9352ab68be13+incompatible
github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e // indirect
github.com/jinzhu/gorm v1.9.12 github.com/jinzhu/gorm v1.9.12
github.com/micro/go-micro v1.18.0 // indirect
github.com/micro/go-micro/v2 v2.5.0 github.com/micro/go-micro/v2 v2.5.0
github.com/micro/micro v1.18.0 // indirect github.com/smartystreets/assertions v0.0.0-20190116191733-b6c0e53d7304 // indirect
github.com/micro/micro/v2 v2.5.0 // indirect github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/micro/protoc-gen-micro/v2 v2.0.0 // indirect github.com/stretchr/testify v1.5.1 // indirect
github.com/shopspring/decimal v1.2.0 // indirect
golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2 // indirect golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2 // indirect
golang.org/x/sys v0.0.0-20200523222454-059865788121 // indirect golang.org/x/sys v0.0.0-20200523222454-059865788121 // indirect
google.golang.org/appengine v1.6.3 // indirect
google.golang.org/genproto v0.0.0-20200527145253-8367513e4ece // indirect google.golang.org/genproto v0.0.0-20200527145253-8367513e4ece // indirect
google.golang.org/grpc v1.29.1 // indirect google.golang.org/grpc v1.29.1 // indirect
google.golang.org/protobuf v1.24.0 google.golang.org/protobuf v1.24.0
gopkg.in/ini.v1 v1.51.0 // indirect
) )
replace google.golang.org/grpc => google.golang.org/grpc v1.26.0 replace google.golang.org/grpc => google.golang.org/grpc v1.26.0
package config package config
import ( import (
"fmt"
"github.com/go-ini/ini" "github.com/go-ini/ini"
"strings"
) )
var ( var (
cfg *ini.File cfg *ini.File
) )
func SetUp(filePath string) { func SetUp() (err error) {
var err error cfg, err = ini.Load("conf/config.ini")
cfg, err = ini.Load(filePath) return
if err != nil {
panic(fmt.Sprintf("解析配置文件失败: %v", err))
}
} }
func GetConfig() *ini.File { func Get(key string) *ini.Key {
return cfg if strings.Contains(key, ".") {
keys := strings.Split(key, ".")
return cfg.Section(keys[0]).Key(keys[1])
}
return cfg.Section("").Key(key)
} }
package e
type FatalError struct {
ErrMsg string
}
func (err *FatalError) Error() string {
return err.ErrMsg
}
func NewFatalError( msg string) *FatalError {
return &FatalError{ ErrMsg: msg}
}
func IsFatalError(err error) bool {
if _,ok:=err.(*FatalError);ok{
return true
}
return false
}
\ No newline at end of file
package gredis
import (
"encoding/json"
"github.com/gomodule/redigo/redis"
"jtthink/pkg/config"
"time"
)
var writeConn, readConn *redis.Pool
func Setup() (err error) {
writeHost := config.Get("redis.write_host").String()
readHost := config.Get("redis.read_host").String()
writePassword := config.Get("redis.write_password").String()
readPassword := config.Get("redis.read_password").String()
writeConn, err = getConn(writeHost, writePassword)
if err != nil {
return
}
readConn, err = getConn(readHost, readPassword)
if err != nil {
return
}
return nil
}
func getConn(writeHost, password string) (pool *redis.Pool, err error) {
maxIdle, _ := config.Get("redis.max_idle").Int()
maxActive, _ := config.Get("redis.max_active").Int()
pool = &redis.Pool{
MaxIdle: maxIdle,
MaxActive: maxActive,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", writeHost)
if err != nil {
return nil, err
}
if password != "" {
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
return
}
//最基础的键值操作
func Set(key string, data interface{}) error {
conn := writeConn.Get()
defer conn.Close()
value, err := json.Marshal(data)
if err != nil {
return err
}
_, err = conn.Do("SET", key, value)
if err != nil {
return err
}
return nil
}
func Exists(key string) bool {
conn := readConn.Get()
defer conn.Close()
exists, err := redis.Bool(conn.Do("EXISTS", key))
if err != nil {
return false
}
return exists
}
func Get(key string) (interface{}, error) {
conn := readConn.Get()
defer conn.Close()
reply, err := conn.Do("GET", key)
if err != nil {
return nil, err
}
return reply, nil
}
func Delete(key string) (bool, error) {
conn := writeConn.Get()
defer conn.Close()
return redis.Bool(conn.Do("DEL", key))
}
//哈希操作
func HSet(key string, k interface{}, data interface{}) error {
conn := writeConn.Get()
defer conn.Close()
value, err := json.Marshal(data)
if err != nil {
return err
}
_, err = conn.Do("HSET", key, k, value)
if err != nil {
return err
}
return nil
}
func HGet(key string, k interface{}) (interface{}, error) {
conn := readConn.Get()
defer conn.Close()
reply, err := conn.Do("HGET", key, k)
if err != nil {
return nil, err
}
return reply, nil
}
func HDelete(key string, k interface{}) (bool, error) {
conn := writeConn.Get()
defer conn.Close()
return redis.Bool(conn.Do("HDEL", key, k))
}
package mysql
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"jtthink/pkg/config"
"jtthink/pkg/e"
)
//mysql相关
var mysqlDb *gorm.DB
func Setup() error {
var err error
userName := config.Get("database.user_name").String()
password := config.Get("database.password").String()
host := config.Get("database.host").String()
database := config.Get("database.database").String()
mysqlDb, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8&parseTime=True&loc=Local",
userName, password, host, database))
if err != nil {
mysqlDb = nil
return e.NewFatalError(err.Error()) //这里返回致命异常
}
mysqlDb.SingularTable(true)
mysqlDb.DB().SetMaxIdleConns(10)
mysqlDb.DB().SetMaxOpenConns(100)
mysqlDb.LogMode(true)
return nil
}
func GetDB() *gorm.DB {
return mysqlDb
}
...@@ -2,13 +2,13 @@ package service ...@@ -2,13 +2,13 @@ package service
import ( import (
"context" "context"
"jtthink/Boot" "jtthink/boot"
. "jtthink/Course" . "jtthink/Course"
) )
type CourseTopicServiceImpl struct {} type CourseTopicServiceImpl struct {}
func(this *CourseTopicServiceImpl) GetTopic(ctx context.Context, in *TopicRequest, out *TopicResponse) error{ func(this *CourseTopicServiceImpl) GetTopic(ctx context.Context, in *TopicRequest, out *TopicResponse) error{
if err:=Boot.GetDB().Table("course_topic").Find(&out.Result).Error;err!=nil { if err:= boot.GetDB().Table("course_topic").Find(&out.Result).Error;err!=nil {
return err return err
} }
return nil return nil
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment