Skip to content
Merged

Dev #108

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.idea*
.DS_Store
cspell.json
config.yaml
.vscode*
wejh-go
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type SubscribeLowBatteryAlertReq struct {
Threshold int `json:"threshold"`
}

// GetBalance 获取电费余额
func GetBalance(c *gin.Context) {
var postForm CampusForm
err := c.ShouldBindQuery(&postForm)
Expand All @@ -41,15 +42,10 @@ func GetBalance(c *gin.Context) {
apiException.AbortWithException(c, apiException.NotBindYxy, nil)
return
}
token, err := yxyServices.GetElecAuthToken(user.YxyUid)
if err != nil {
apiException.AbortWithException(c, apiException.ServerError, err)
return
}
if postForm.Campus != "mgs" {
postForm.Campus = "zhpf"
}
balance, err := yxyServices.ElectricityBalance(*token, postForm.Campus)
balance, err := yxyServices.ElectricityBalance(user.YxyUid, postForm.Campus)
if errors.Is(err, apiException.NotBindCard) {
_ = yxyServices.Unbind(user.ID, user.YxyUid, true)
apiException.AbortWithError(c, err)
Expand All @@ -64,6 +60,7 @@ func GetBalance(c *gin.Context) {
utils.JsonSuccessResponse(c, balance)
}

// GetRechargeRecords 获取充值记录
func GetRechargeRecords(c *gin.Context) {
var postForm recordForm
err := c.ShouldBindJSON(&postForm)
Expand All @@ -80,15 +77,10 @@ func GetRechargeRecords(c *gin.Context) {
apiException.AbortWithException(c, apiException.NotBindYxy, nil)
return
}
token, err := yxyServices.GetElecAuthToken(user.YxyUid)
if err != nil {
apiException.AbortWithException(c, apiException.ServerError, err)
return
}
if postForm.Campus != "mgs" {
postForm.Campus = "zhpf"
}
roomStrConcat, err := yxyServices.GetElecRoomStrConcat(*token, postForm.Campus, user.YxyUid)
roomStrConcat, err := yxyServices.GetElecRoomStrConcat(user.YxyUid, postForm.Campus)
if errors.Is(err, apiException.NotBindCard) {
_ = yxyServices.Unbind(user.ID, user.YxyUid, true)
apiException.AbortWithError(c, err)
Expand All @@ -100,7 +92,7 @@ func GetRechargeRecords(c *gin.Context) {
apiException.AbortWithException(c, apiException.ServerError, err)
return
}
records, err := yxyServices.ElectricityRechargeRecords(*token, postForm.Campus, postForm.Page, *roomStrConcat)
records, err := yxyServices.ElectricityRechargeRecords(user.YxyUid, postForm.Campus, postForm.Page, *roomStrConcat)
if errors.Is(err, apiException.CampusMismatch) {
apiException.AbortWithError(c, err)
return
Expand All @@ -111,10 +103,10 @@ func GetRechargeRecords(c *gin.Context) {
utils.JsonSuccessResponse(c, records.List)
}

// GetConsumptionRecords 获取电费使用记录
func GetConsumptionRecords(c *gin.Context) {
var postForm CampusForm
err := c.ShouldBindQuery(&postForm)
if err != nil {
if err := c.ShouldBindQuery(&postForm); err != nil {
apiException.AbortWithException(c, apiException.ParamError, err)
return
}
Expand All @@ -127,15 +119,10 @@ func GetConsumptionRecords(c *gin.Context) {
apiException.AbortWithException(c, apiException.NotBindYxy, nil)
return
}
token, err := yxyServices.GetElecAuthToken(user.YxyUid)
if err != nil {
apiException.AbortWithException(c, apiException.ServerError, err)
return
}
if postForm.Campus != "mgs" {
postForm.Campus = "zhpf"
}
roomStrConcat, err := yxyServices.GetElecRoomStrConcat(*token, postForm.Campus, user.YxyUid)
roomStrConcat, err := yxyServices.GetElecRoomStrConcat(user.YxyUid, postForm.Campus)
if errors.Is(err, apiException.NotBindCard) {
_ = yxyServices.Unbind(user.ID, user.YxyUid, true)
apiException.AbortWithError(c, err)
Expand All @@ -147,7 +134,7 @@ func GetConsumptionRecords(c *gin.Context) {
apiException.AbortWithException(c, apiException.ServerError, err)
return
}
records, err := yxyServices.GetElecConsumptionRecords(*token, postForm.Campus, *roomStrConcat)
records, err := yxyServices.GetElecConsumptionRecords(user.YxyUid, postForm.Campus, *roomStrConcat)
if errors.Is(err, apiException.CampusMismatch) {
apiException.AbortWithError(c, err)
return
Expand Down
56 changes: 7 additions & 49 deletions app/services/yxyServices/cacheService.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,22 @@ package yxyServices
import (
"context"
"encoding/json"
"errors"
"time"
r "wejh-go/config/redis"

"golang.org/x/sync/singleflight"

"github.com/go-redis/redis/v8"
)

var (
ctx = context.Background()
g singleflight.Group
)

func GetElecRoomStrConcat(token, campus, yxyUid string) (*string, error) {
func GetElecRoomStrConcat(yxyUid, campus string) (*string, error) {
cacheKey := "elec:room_str_concat:" + campus + ":" + yxyUid
cachedRoomStrConcat, err := r.RedisClient.Get(ctx, cacheKey).Result()
if err == redis.Nil {
balance, err := ElectricityBalance(token, campus)
if errors.Is(err, redis.Nil) {
balance, err := ElectricityBalance(yxyUid, campus)
if err != nil {
return nil, err
}
Expand All @@ -35,37 +33,11 @@ func GetElecRoomStrConcat(token, campus, yxyUid string) (*string, error) {
return &cachedRoomStrConcat, nil
}

func GetElecAuthToken(yxyUid string) (*string, error) {
cacheKey := "elec:auth_token:" + yxyUid
cachedToken, err := r.RedisClient.Get(ctx, cacheKey).Result()
if err == redis.Nil {
// 使用 singleflight 防止缓存击穿
token, err, _ := g.Do(cacheKey, func() (interface{}, error) {
t, e := Auth(yxyUid)
if e != nil {
return nil, e
}
e = r.RedisClient.Set(ctx, cacheKey, *t, 7*24*time.Hour).Err()
if e != nil {
return nil, e
}
return t, nil
})
if err != nil {
return nil, err
}
return token.(*string), nil
} else if err != nil {
return nil, err
}
return &cachedToken, nil
}

func GetElecConsumptionRecords(token, campus, roomStrConcat string) (*EleConsumptionRecords, error) {
func GetElecConsumptionRecords(yxyUid, campus, roomStrConcat string) (*EleConsumptionRecords, error) {
cacheKey := "elec:consumption_records:" + roomStrConcat
cachedRecords, err := r.RedisClient.Get(ctx, cacheKey).Result()
if err == redis.Nil {
records, err := ElectricityConsumptionRecords(token, campus, roomStrConcat)
if errors.Is(err, redis.Nil) {
records, err := ElectricityConsumptionRecords(yxyUid, campus, roomStrConcat)
if err != nil {
return nil, err
}
Expand All @@ -91,17 +63,3 @@ func GetElecConsumptionRecords(token, campus, roomStrConcat string) (*EleConsump
}
return &records, nil
}

func SetCardAuthToken(yxyUid, token string) error {
cacheKey := "card:auth_token:" + yxyUid
return r.RedisClient.Set(ctx, cacheKey, token, 7*24*time.Hour).Err()
}

func GetCardAuthToken(yxyUid string) (*string, error) {
cacheKey := "card:auth_token:" + yxyUid
cachedToken, err := r.RedisClient.Get(ctx, cacheKey).Result()
if err == redis.Nil {
return nil, err
}
return &cachedToken, nil
}
37 changes: 6 additions & 31 deletions app/services/yxyServices/electricityService.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ import (
"github.com/mitchellh/mapstructure"
)

type AuthResp struct {
Token string `json:"token" mapstructure:"token"`
}

type ElecBalance struct {
DisplayRoomName string `json:"display_room_name" mapstructure:"display_room_name"`
RoomStrConcat string `json:"room_str_concat" mapstructure:"room_str_concat"`
Expand All @@ -32,34 +28,13 @@ type EleConsumptionRecords struct {
} `json:"list" mapstructure:"list"`
}

func Auth(uid string) (*string, error) {
params := url.Values{}
Url, err := url.Parse(string(yxyApi.Auth))
if err != nil {
return nil, err
}
params.Set("uid", uid)
Url.RawQuery = params.Encode()
urlPath := Url.String()
resp, err := FetchHandleOfGet(yxyApi.YxyApi(urlPath))
if err != nil {
return nil, err
}
var data AuthResp
err = mapstructure.Decode(resp.Data, &data)
if err != nil {
return nil, err
}
return &data.Token, nil
}

func ElectricityBalance(token, campus string) (*ElecBalance, error) {
func ElectricityBalance(uid, campus string) (*ElecBalance, error) {
params := url.Values{}
Url, err := url.Parse(string(yxyApi.ElectricityBalance))
if err != nil {
return nil, err
}
params.Set("token", token)
params.Set("uid", uid)
params.Set("campus", campus)
Url.RawQuery = params.Encode()
urlPath := Url.String()
Expand All @@ -82,13 +57,13 @@ func ElectricityBalance(token, campus string) (*ElecBalance, error) {
return &data, nil
}

func ElectricityRechargeRecords(token, campus, page, roomStrConcat string) (*RechargeRecords, error) {
func ElectricityRechargeRecords(uid, campus, page, roomStrConcat string) (*RechargeRecords, error) {
params := url.Values{}
Url, err := url.Parse(string(yxyApi.RechargeRecords))
if err != nil {
return nil, err
}
params.Set("token", token)
params.Set("uid", uid)
params.Set("campus", campus)
params.Set("page", page)
params.Set("room_str_concat", roomStrConcat)
Expand All @@ -111,13 +86,13 @@ func ElectricityRechargeRecords(token, campus, page, roomStrConcat string) (*Rec
return &data, nil
}

func ElectricityConsumptionRecords(token, campus, roomStrConcat string) (*EleConsumptionRecords, error) {
func ElectricityConsumptionRecords(uid, campus, roomStrConcat string) (*EleConsumptionRecords, error) {
params := url.Values{}
Url, err := url.Parse(string(yxyApi.ElectricityConsumption))
if err != nil {
return nil, err
}
params.Set("token", token)
params.Set("uid", uid)
params.Set("campus", campus)
params.Set("room_str_concat", roomStrConcat)
Url.RawQuery = params.Encode()
Expand Down
5 changes: 4 additions & 1 deletion app/utils/circuitBreaker/circuitBreaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ type CircuitBreaker struct {
SnapShot *sync.Map
}

func init() {
func Init() {

Probe = NewLiveNessProbe(cbConfig.GetLiveNessConfig())

lb := LoadBalance{
zfLB: &randomLB{},
oauthLB: &randomLB{},
Expand Down
4 changes: 0 additions & 4 deletions app/utils/circuitBreaker/liveNessProbe.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ import (

var Probe *LiveNessProbe

func init() {
Probe = NewLiveNessProbe(cbConfig.GetLiveNessConfig())
}

type LiveNessProbe struct {
sync.Mutex
ApiMap map[string]funnelApi.LoginType
Expand Down
3 changes: 2 additions & 1 deletion config/config/config.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package config

import (
"github.com/spf13/viper"
"log"

"github.com/spf13/viper"
)

var Config = viper.New()
Expand Down
2 changes: 1 addition & 1 deletion config/redis/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type redisConfig struct {
var RedisClient *redis.Client
var RedisInfo redisConfig

func init() {
func Init() {
info := getConfig()

RedisClient = redis.NewClient(&redis.Options{
Expand Down
4 changes: 1 addition & 3 deletions config/wechat/wechat.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,16 @@ const (

var MiniProgram *miniprogram.MiniProgram

func init() {
func Init() {
config := getConfigs()

wc := wechat.NewWechat()
var wcCache cache.Cache
switch config.Driver {
case string(Redis):
wcCache = setRedis(wcCache)
break
case string(Memory):
wcCache = cache.NewMemory()
break
default:
zap.L().Fatal("Config Error")
}
Expand Down
13 changes: 10 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@ package main
import (
"context"
"errors"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"log"
"net/http"
"os/signal"
Expand All @@ -17,15 +14,25 @@ import (
"wejh-go/config/config"
"wejh-go/config/database"
"wejh-go/config/logger"
"wejh-go/config/redis"
"wejh-go/config/router"
"wejh-go/config/session"
"wejh-go/config/wechat"

"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)

func main() {
if err := logger.Init(); err != nil {
log.Fatal(err.Error())
}
redis.Init()
database.Init()
circuitBreaker.Init()
wechat.Init()

r := gin.Default()
r.Use(cors.Default())
r.Use(midwares.ErrHandler())
Expand Down