import (
"github.com/gin-gonic/gin"
"github.com/go-redis/redis"
"github.com/Shopify/sarama"
)
func GrabOrder(c *gin.Context) {
// redis预减库存
client := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
})
key := "order_stock"
res, err := client.Decr(key).Result()
if err != nil {
c.JSON(http.StatusInternalServerError, err)
return
}
if res < 0 {
c.JSON(http.StatusOK, gin.H{
"code": -1,
"msg": "库存不足",
})
return
}
// 异步发送kafka消息,记录订单
producer, err := sarama.NewSyncProducer([]string{"127.0.0.1:9092"}, nil)
if err != nil {
c.JSON(http.StatusInternalServerError, err)
return
}
defer producer.Close()
msg := &sarama.ProducerMessage{
Topic: "order_topic",
Value: sarama.StringEncoder("order_data"),
}
_, _, err = producer.SendMessage(msg)
if err != nil {
c.JSON(http.StatusInternalServerError, err)
return
}
// 返回抢购结果
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "抢购成功",
})
return
}