dao.go 1.91 KB
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
package dao

import (
	"context"
	"github.com/go-kratos/kratos/contrib/registry/consul/v2"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/google/wire"
	"gorm.io/gorm"
	"hilo/api/service/country"
	"hilo/api/service/mgr"
	"hilo/app/service/user/internal/conf"
	"hilo/common/httpclient"
	"hilo/common/mysql"
	"hilo/common/redis"
	"net/http"
	"time"
)

var ProviderSet = wire.NewSet(NewDao, NewCountryClient, NewMgrClient)

// Dao .
type Dao struct {
	DB            *gorm.DB
	Redis         *redis.WrapClient
	Http          *http.Client
	MgrClient     mgr.MgrClient
	CountryClient country.CountryClient
}

func NewDao(c *conf.Data, countryClient country.CountryClient, mgrClient mgr.MgrClient) (*Dao, func(), error) {
	db := mysql.NewDB(c.Mysql)
	rs := redis.NewRedis(c.Redis)
	httpClient := httpclient.NewClient()

	cleanup := func() {
		d, _ := db.DB()
		d.Close()
		rs.Client.Close()
		httpClient.CloseIdleConnections()
		log.Debug("close Dao resources")
	}

	return &Dao{
		DB:            db,
		Redis:         rs,
		Http:          httpClient,
		CountryClient: countryClient,
		MgrClient:     mgrClient,
	}, cleanup, nil
}

func NewMgrClient(conf *conf.Client, rr *consul.Registry) mgr.MgrClient {
	conn, err := grpc.DialInsecure(
		context.Background(),
		grpc.WithEndpoint(conf.Mgr.Endpoint),
		grpc.WithDiscovery(rr),
		grpc.WithMiddleware(
			recovery.Recovery(),
		),
		grpc.WithTimeout(time.Second*2),
	)
	if err != nil {
		panic(err)
	}
	return mgr.NewMgrClient(conn)
}

func NewCountryClient(conf *conf.Client, rr *consul.Registry) country.CountryClient {
	conn, err := grpc.DialInsecure(
		context.Background(),
		grpc.WithEndpoint(conf.Country.Endpoint),
		grpc.WithDiscovery(rr),
		grpc.WithMiddleware(
			recovery.Recovery(),
		),
		grpc.WithTimeout(time.Second*2),
	)
	if err != nil {
		panic(err)
	}
	return country.NewCountryClient(conn)
}