69 lines
2.2 KiB
Go
69 lines
2.2 KiB
Go
package svc
|
||
|
||
import (
|
||
"fmt"
|
||
"github.com/smartwalle/alipay/v3"
|
||
"github.com/zeromicro/go-zero/core/logx"
|
||
"github.com/zeromicro/go-zero/core/stores/redis"
|
||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||
"github.com/zeromicro/go-zero/zrpc"
|
||
"tianyuan-api/apps/sentinel/internal/config"
|
||
"tianyuan-api/apps/sentinel/internal/model"
|
||
"tianyuan-api/apps/user/user"
|
||
)
|
||
|
||
type ServiceContext struct {
|
||
Config config.Config
|
||
Redis *redis.Redis
|
||
AlipayClient *alipay.Client
|
||
WhitelistModel model.WhitelistModel
|
||
SecretsModel model.SecretsModel
|
||
ProductsModel model.ProductsModel
|
||
UserProductsModel model.UserProductsModel
|
||
PayOrderModel model.PayOrderModel
|
||
WalletRpc user.WalletServiceClient
|
||
}
|
||
|
||
func NewServiceContext(c config.Config) *ServiceContext {
|
||
db := sqlx.NewMysql(c.DataSource) // 创建数据库连接
|
||
redisConf := redis.RedisConf{
|
||
Host: c.CacheRedis[0].Host,
|
||
Pass: c.CacheRedis[0].Pass,
|
||
Type: c.CacheRedis[0].Type, // Redis 节点类型,如 "node"
|
||
}
|
||
// 使用 MustNewRedis 来初始化 Redis 客户端
|
||
rds := redis.MustNewRedis(redisConf)
|
||
|
||
// 创建支付宝客户端
|
||
client, err := alipay.New(c.Alipay.AppID, c.Alipay.PrivateKey, c.Alipay.IsProduction)
|
||
if err != nil {
|
||
panic(fmt.Sprintf("创建支付宝客户端失败: %v", err))
|
||
}
|
||
|
||
// 加载支付宝公钥
|
||
err = client.LoadAliPayPublicKey(c.Alipay.AlipayPublicKey)
|
||
if err != nil {
|
||
panic(fmt.Sprintf("加载支付宝公钥失败: %v", err))
|
||
}
|
||
var walletRpc user.WalletServiceClient
|
||
|
||
// 捕获RPC初始化时的错误,但不影响服务启动
|
||
userClient, err := zrpc.NewClient(c.UserRpc)
|
||
if err != nil {
|
||
logx.Errorf("Failed to connect to SecretRpc: %v", err)
|
||
} else {
|
||
walletRpc = user.NewWalletServiceClient(userClient.Conn())
|
||
}
|
||
return &ServiceContext{
|
||
Config: c,
|
||
Redis: rds,
|
||
AlipayClient: client,
|
||
WhitelistModel: model.NewWhitelistModel(rds, db, c.CacheRedis),
|
||
SecretsModel: model.NewSecretsModel(db, c.CacheRedis),
|
||
ProductsModel: model.NewProductsModel(db, c.CacheRedis),
|
||
UserProductsModel: model.NewUserProductsModel(rds, db, c.CacheRedis),
|
||
PayOrderModel: model.NewPayOrderModel(db, c.CacheRedis),
|
||
WalletRpc: walletRpc,
|
||
}
|
||
}
|