Wordpress跨应用调取Magento产品数据

我这里有个需求就是Wordpress调取Magento的产品价格,并且Wordpress流量巨大(日均PV千万+)。
这里我使用Golang作为一个单独的服务给Wordpress提供数据,使用的是之前介绍过的:
https://forum.magentochina.org/t/%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%E6%8E%A8%E8%8D%90magento2-api-golang/889/2

Go端我使用gin作为web框架,并使用了PageCache抵御巨量访问请求,然后通过上面的API库使用reset API读取Magento2的数据。

话不多说,代码如下:


package main

import (
	"net/http"
	"github.com/gin-contrib/cache"
	"github.com/gin-contrib/cache/persistence"
	"github.com/gin-gonic/gin"
	"github.com/hermsi1337/go-magento2"
	"time"
)
// start gin framework

func setupRouter() *gin.Engine {
	//init gin 
	r := gin.Default()
	store := persistence.NewInMemoryStore(time.Second)
	r.GET("/sku/:sku", cache.CachePage(store, 5 * time.Minute, func(c *gin.Context) {
		SKU := c.Params.ByName("sku")
		if SKU != ""{
			respond := make(map[string]interface{})
			respond["Price"] = GetProductInfoBySKU(SKU)
			c.JSON(200, gin.H{"200": respond} )
			//log.Println(GetProductInfoBySKU(SKU))
		}else{
			c.JSON(http.StatusNotFound, gin.H{"message": "not found"})
		}
		
	}))
	return r
}

//GetProductInfoBySKU is Get product infomation By SKU.
func GetProductInfoBySKU(SKU string)(Price float64){
	// initiate storeconfig.
	storeConfig := &magento2.StoreConfig{
		Scheme:    "https",
		HostName:  "www.mywebsite.com",
		StoreCode: "default",
	}
	// initiate bearer payload
	bearerToken := "your magento token from adminplan"
	// create a new apiClient
	apiClient, err := magento2.NewAPIClientFromIntegration(storeConfig, bearerToken)
	if err != nil {
		panic(err)
	}
	// get product by SKU
		mProduct, err := magento2.GetProductBySKU(SKU, apiClient)
		if err != nil {
			panic(err)
		}
		Price = mProduct.Product.Price
	
//	log.Println(mProduct.Product.ProductLinks)
	return Price
}
func main() {
	r := setupRouter()
	r.Run("127.0.0.1:8080")
}

结果:



初始化的时候速度大于2s,后续查找小于1s。在有cache的情况下,response速度为纳秒级。
飞一般的速度。

Wordpress端不是本文重点,返回的Json自行处理。