這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
config.ini 設定檔
[stomp];activemq的IP地址host:192.168.7.85 ;activemq的連接埠port:61613 ;activemq的隊列queue:/queue/bbg_ordercache [php];php的執行路徑phpbin:php.exe;被執行的檔案的路徑 filepath:D:/jianguo/command/application/cli ;傳遞給被執行檔案的參數params:show
main.go 代碼檔案:
package mainimport ("bytes""fmt""github.com/gmallard/stompngo""github.com/unknwon/goconfig""log""net""os""os/exec")// 儲存配置資訊的變數var config *goconfig.ConfigFile// 儲存日誌資訊的變數var mylog *log.Logger// 啟動初始化func init() {// 載入設定檔configPath := "./config.ini"conf, err := goconfig.LoadConfigFile(configPath)if err != nil {fmt.Println(err)}config = conf// @todo 強化按日期寫記錄檔file := "./log.txt"//t := time.Now()//file := "./log_" + strings.Replace(t.String()[:19], ":", "_", 3) + ".txt"hander, err := os.OpenFile(file, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)if err != nil {log.Println(err)}mylog = log.New(hander, "\r\n", log.Ldate|log.Ltime|log.Llongfile)}// 主程式func main() {host, _ := config.GetValue("stomp", "host")port, _ := config.GetValue("stomp", "port")n, e := net.Dial("tcp", net.JoinHostPort(host, port))if e != nil {fmt.Println(e)}// STOMP 1.0 的標準頭//h := stompngo.Headers{}// STOMP 1.1 的標準頭h := stompngo.Headers{"accept-version", "1.1"}// @todo 強化網路斷開之後重試c, e := stompngo.Connect(n, h)if e != nil {fmt.Println(e)}// 必須用戶端響應才可以刪除MQ隊列資料f := stompngo.Headers{"destination", "/queue/bbg_ordercache", "ack", "client"}// 自動刪除MQ隊列的資料//f := stompngo.Headers{"destination", "/queue/bbg_ordercache"}s, e := c.Subscribe(f)if e != nil {fmt.Println(e)}// 設定通道的容量//fmt.Println(c.SubChanCap())//c.SetSubChanCap(1)for {//r := <-s//fmt.Println(r)run(c, s)}}// 外部shell指令碼調用,成功處理刪除相應隊列func run(c *stompngo.Connection, s <-chan stompngo.MessageData) {phproot, _ := config.GetValue("php", "phpbin")filepath, _ := config.GetValue("php", "filepath")params, _ := config.GetValue("php", "params")r := <-s// 記錄結果mylog.Println(r)order_id := r.Message.Headers.Value("order_id")//fmt.Println(order_id)cmd := exec.Command(phproot, filepath, params, "order_id", order_id)var out bytes.Buffercmd.Stdout = &outerr := cmd.Start()if err != nil {log.Fatal(err)}mylog.Println("Waiting for command to finish...")err = cmd.Wait()if err != nil {mylog.Printf("Command finished with error: %v", err)}str := out.String()//fmt.Println(str)if str == "success" {e := c.Ack(r.Message.Headers)if e != nil {mylog.Println(e)}}}