修改ProdService.go(实际业务),延迟生成数据
func (s *ProdService) GetProdList(c context.Context, in *Services.ProdRequest, res *Services.ProdListResponse) error {
time.Sleep(time.Second * 3) // hystrix使用 模拟延迟
models := make([]*Services.ProdModel, 0)
var i int32
for i = 0; i < in.Size; i++ {
models = append(models, newProd(i+100, "ProdName"+strconv.Itoa(int(i)+100)))
}
res.Data = models
return nil
}
修改ProdService.go(调用业务的)
package Server
import (
"context"
"gitee.com/Hind3ight/easy-go-micro/go-micro/Services"
"github.com/afex/hystrix-go/hystrix"
"github.com/gin-gonic/gin"
)
func GetProdListServer(c *gin.Context) {
prodService := c.Keys["prodService"].(Services.ProdService)
var prodReq Services.ProdRequest
err := c.Bind(&prodReq)
if err != nil {
c.JSON(500, gin.H{"status": err.Error()})
} else {
// 临时改造 熔断
// 1. 配置 config
configA := hystrix.CommandConfig{
Timeout:2000,
}
// 2. 配置command
hystrix.ConfigureCommand("getProds",configA)
// 3. 执行Do方法
var prodRes *Services.ProdListResponse
err := hystrix.Do("getProds", func() error {
prodRes, err = prodService.GetProdList(context.Background(), &prodReq)
return err
}, nil)
if err != nil {
c.JSON(500, gin.H{"status": err.Error()})
} else {
c.JSON(200, gin.H{"data": prodRes.Data})
}
}
}