wskickahn 发表于 2018-9-19 12:06:05

Go语言学习笔记(八)golang 操作 Redis & Mysql & RabbitMQ

package main  

  
import (
  

"fmt"  
"log"
  
"math/rand"
  
"os"
  
"strconv"
  
"strings"
  
"time"
  

  
"github.com/streadway/amqp"
  
)
  

  
/*
  
RPC模式
  
请求方
  
*/
  

  
func failOnError(err error, msg string) {
  
if err != nil {
  
log.Fatalf("%s: %s", msg, err)
  
panic(fmt.Sprintf("%s: %s", msg, err))
  
}
  
}
  

  
func randomString(l int) string {
  
bytes := make([]byte, l)
  
for i := 0; i < l; i++ {
  
bytes = byte(randInt(65, 90))
  
}
  
return string(bytes)
  
}
  

  
func randInt(min int, max int) int {
  
return min + rand.Intn(max-min)
  
}
  

  
func fibonacciRPC(n int) (res int, err error) {
  

  
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
  
failOnError(err, "Failed to connect to RabbitMQ")
  
defer conn.Close()
  

  
ch, err := conn.Channel()
  
failOnError(err, "Failed to open a channel")
  
defer ch.Close()
  

  
// 队列声明
  
q, err := ch.QueueDeclare(
  
"",    // name
  
false, // durable
  
false, // delete when usused
  
true,// exclusive 为真即连接断开就删除
  
false, // noWait
  
nil,   // arguments
  
    )
  
failOnError(err, "Failed to declare a queue")
  

  
msgs, err := ch.Consume(
  
q.Name, // queue
  
"",   // consumer
  
true,   // auto-ack
  
false,// exclusive   这个为真,服务器会认为这是该队列唯一的消费者
  
false,// no-local
  
false,// no-wait
  
nil,    // args
  
    )
  
failOnError(err, "Failed to register a consumer")
  

  
corrId := randomString(32)
  

  
err = ch.Publish(
  
"",          // exchange
  
"rpc_queue", // routing key
  
false,       // mandatory
  
false,       // immediate
  
      amqp.Publishing{
  
ContentType:   "text/plain",
  
CorrelationId: corrId,
  
ReplyTo:       q.Name,
  
Body:          []byte(strconv.Itoa(n)),
  
})
  
failOnError(err, "Failed to publish a message")
  

  
for d := range msgs {
  
if corrId == d.CorrelationId {
  
res, err = strconv.Atoi(string(d.Body))
  
failOnError(err, "Failed to convert body to integer")
  
break
  
}
  
}
  

  
return
  
}
  

  
func main() {
  
rand.Seed(time.Now().UTC().UnixNano())
  

  
n := bodyFrom(os.Args)
  

  
log.Printf(" Requesting fib(%d)", n)
  
res, err := fibonacciRPC(n)
  
failOnError(err, "Failed to handle RPC request")
  

  
log.Printf(" [.] Got %d", res)
  
}
  

  
func bodyFrom(args []string) int {
  
var s string
  
if (len(args) < 2) || os.Args == "" {
  
s = "30"
  
} else {
  
s = strings.Join(args, " ")
  
}
  
n, err := strconv.Atoi(s)
  
failOnError(err, "Failed to convert arg to integer")
  
return n
  
}


页: [1]
查看完整版本: Go语言学习笔记(八)golang 操作 Redis & Mysql & RabbitMQ