• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang amqp.Connection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/streadway/amqp.Connection的典型用法代码示例。如果您正苦于以下问题:Golang Connection类的具体用法?Golang Connection怎么用?Golang Connection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Connection类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Connect

func (q *AMQP) Connect() error {
	q.Lock()
	defer q.Unlock()

	q.headers = amqp.Table{
		"precision":        q.Precision,
		"database":         q.Database,
		"retention_policy": q.RetentionPolicy,
	}

	var connection *amqp.Connection
	// make new tls config
	tls, err := internal.GetTLSConfig(
		q.SSLCert, q.SSLKey, q.SSLCA, q.InsecureSkipVerify)
	if err != nil {
		return err
	}

	if tls != nil {
		connection, err = amqp.DialTLS(q.URL, tls)
	} else {
		connection, err = amqp.Dial(q.URL)
	}
	if err != nil {
		return err
	}
	channel, err := connection.Channel()
	if err != nil {
		return fmt.Errorf("Failed to open a channel: %s", err)
	}

	err = channel.ExchangeDeclare(
		q.Exchange, // name
		"topic",    // type
		true,       // durable
		false,      // delete when unused
		false,      // internal
		false,      // no-wait
		nil,        // arguments
	)
	if err != nil {
		return fmt.Errorf("Failed to declare an exchange: %s", err)
	}
	q.channel = channel
	go func() {
		log.Printf("Closing: %s", <-connection.NotifyClose(make(chan *amqp.Error)))
		log.Printf("Trying to reconnect")
		for err := q.Connect(); err != nil; err = q.Connect() {
			log.Println(err)
			time.Sleep(10 * time.Second)
		}

	}()
	return nil
}
开发者ID:cwegener,项目名称:telegraf,代码行数:55,代码来源:amqp.go


示例2: NewServerCodec

//NewServerCodec returns a new rpc.ClientCodec using AMQP on conn. serverRouting is the routing
//key with with RPC calls are received, encodingCodec is an EncodingCoding implementation. This package provdes JSONCodec and GobCodec for the JSON and Gob encodings respectively.
func NewServerCodec(conn *amqp.Connection, serverRouting string, encodingCodec EncodingCodec) (rpc.ServerCodec, error) {
	channel, err := conn.Channel()
	if err != nil {
		return nil, err
	}

	queue, err := channel.QueueDeclare(serverRouting, false, false, false, false, nil)
	if err != nil {
		return nil, err
	}

	messages, err := channel.Consume(queue.Name, "", true, false, false, false, nil)
	if err != nil {
		return nil, err
	}

	server := &serverCodec{
		codec: &codec{
			conn:    conn,
			channel: channel,
			routing: queue.Name,

			codec:   encodingCodec,
			message: messages,
		},
		lock:  new(sync.RWMutex),
		calls: make(map[uint64]route),
		seq:   0,
	}

	return server, err
}
开发者ID:vibhavp,项目名称:amqp-rpc,代码行数:34,代码来源:server.go


示例3: ServeConn

func (server *Server) ServeConn(conn *amqp.Connection, queue string) {
	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	q, err := ch.QueueDeclare(
		queue, // name
		false, // durable
		false, // delete when usused
		false, // exclusive
		false, // noWait
		nil,   // arguments
	)
	failOnError(err, "Failed to declare a queue")
	msgs, err := ch.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // autoAck
		false,  // exclusive
		false,  // noLocal
		false,  // noWait
		nil,    // arguments
	)
	failOnError(err, "Failed to register a consumer")
	codec := &serverCodec{
		conn:    conn,
		ch:      ch,
		msgs:    msgs,
		pending: make(map[uint64]prop),
	}
	server.s.ServeCodec(codec)
}
开发者ID:pakudayo,项目名称:mqrpc,代码行数:30,代码来源:server.go


示例4: NewClientCodec

//NewClientCodec returns a new rpc.ClientCodec using AMQP on conn. serverRouting is the routing
//key with with RPC calls are sent, it should be the same routing key used with NewServerCodec.
//encodingCodec is an EncodingCoding implementation. This package provdes JSONCodec and GobCodec
//for the JSON and Gob encodings respectively.
func NewClientCodec(conn *amqp.Connection, serverRouting string, encodingCodec EncodingCodec) (rpc.ClientCodec, error) {
	channel, err := conn.Channel()
	if err != nil {
		return nil, err
	}

	queue, err := channel.QueueDeclare("", false, true, false, false, nil)
	if err != nil {
		return nil, err
	}

	serverQueue, err := channel.QueueDeclare(serverRouting, false, false, false, false, nil)
	if err != nil {
		return nil, err
	}
	if serverQueue.Consumers == 0 {
		return nil, ErrNoConsumers
	}

	message, err := channel.Consume(queue.Name, "", true, false, false, false, nil)
	client := &clientCodec{
		codec: &codec{
			conn:    conn,
			channel: channel,
			routing: queue.Name,
			codec:   encodingCodec,
			message: message,
		},

		serverRouting: serverRouting,
	}

	return client, err
}
开发者ID:vibhavp,项目名称:amqp-rpc,代码行数:38,代码来源:client.go


示例5: monitoring

func monitoring(uri string, queueName string, mgmtUri string, prefix string) {
	var (
		queueConn *amqp.Connection
		queueChan *amqp.Channel
		err       error
	)
	queueConn, queueChan, err = rabbitmqConnect(uri, queueName)
	if err != nil {
		return
	}
	for {
		log.Printf("fetch rabbitmq stats")
		var metrics []graphite.Metric
		for _, metric := range fetchQueueMetrics(mgmtUri, prefix) {
			metrics = append(metrics, metric)
		}
		for _, metric := range fetchExchangeMetrics(mgmtUri, prefix) {
			metrics = append(metrics, metric)
		}
		for _, metric := range metrics {
			body := []byte(metric.Name + "\t" + metric.Value + "\t" + strconv.FormatInt(metric.Timestamp, 10))
			msg := amqp.Publishing{ContentType: "text/plain", Body: body}
			err = queueChan.Publish("", queueName, false, false, msg)
			if err != nil {
				log.Printf("publish err: %s", err)
				return
			}
			//log.Printf("metric\t%s\t\t%s", metric.Name, metric.Value)
		}
		time.Sleep(time.Second * 5)
	}
	queueChan.Close()
	queueConn.Close()
}
开发者ID:naveenlj,项目名称:rabbitmq-graphite-tool,代码行数:34,代码来源:rabbitmq-graphite-tool.go


示例6: CreateHelloTopology

func CreateHelloTopology(connection *amqp.Connection) (*amqp.Channel, error) {
	channel, err := connection.Channel()
	if err != nil {
		log.Println("Failed to get channel!: ", err)
		return nil, err
	}

	err = channel.ExchangeDeclare("hello-exchange", "direct", true, false, false, false, nil)
	if err != nil {
		log.Println("Failed to declare exchange!: ", err)
		return nil, err
	}

	_, err = channel.QueueDeclare("hello-queue", false, false, false, false, nil)
	if err != nil {
		log.Println("Failed to declare queue!: ", err)
		return nil, err
	}

	err = channel.QueueBind("hello-queue", "hola", "hello-exchange", false, nil)
	if err != nil {
		log.Println("Failed to bind to queue!: ", err)
		return nil, err
	}

	return channel, nil
}
开发者ID:meatballhat,项目名称:box-o-sand,代码行数:27,代码来源:hello.go


示例7: newConsumeChannel

func newConsumeChannel(conn *amqp.Connection, queueName string) (<-chan amqp.Delivery, error) {
	ch, err := conn.Channel()
	if err != nil {
		return nil, err
	}
	return ch.Consume(queueName, "", false, false, false, false, nil)
}
开发者ID:deviozc,项目名称:amqp-simplelogger,代码行数:7,代码来源:consumer.go


示例8: newPublisher

/*
If ch is nil, a new Connection and Channel will be created, and this publisher
will 'own' the connection. A call to close() will close both channel and connection.

If ch is provided, then this publisher will reuse the channel and
calls to close() will do nothing.
*/
func newPublisher(serverURI string, cfg *ChannelConfig, ch *amqp.Channel) *Publisher {

	var conn *amqp.Connection
	var err error

	if ch == nil {
		conn, err = amqp.Dial(serverURI)
		if err != nil {
			panic(fmt.Errorf("Failed to connect to RabbitMQ: %v", err))
		}

		ch, err = conn.Channel()
		if err != nil {
			panic(fmt.Errorf("Failed to open a channel: %v", err))
		}
	}

	_, err = ch.QueueDeclare(*cfg.Name, *cfg.Durable, *cfg.AutoDelete, *cfg.Exclusive, false, *cfg.Args)
	if err != nil {
		panic(fmt.Errorf("Failed to declare queue %s: %v", cfg.Name, err))
	}

	ch.QueuePurge(*cfg.Name, true)
	return &Publisher{exch: "", routingKey: *cfg.Name, conn: conn, ch: ch, typeTag: *cfg.TypeTag}
}
开发者ID:robinpercy,项目名称:amqpbeat,代码行数:32,代码来源:amqpbeat_test.go


示例9: openChannel

// openChannel opens up a RabbitMQ channel.
func openChannel(conn *amqp.Connection) *amqp.Channel {
	ch, err := conn.Channel()
	if err != nil {
		log.Fatalf("Failed to open a channel: %s", err)
	}
	return ch
}
开发者ID:halafi,项目名称:gomatch,代码行数:8,代码来源:amqp.go


示例10: Consume

func Consume(connection *amqp.Connection, queue string, outChannel chan *protobuf.Notification) {
	// create a channel on this connection
	channel, err := connection.Channel()
	if err != nil {
		panic(err)
	}
	defer channel.Close()

	// start consuming data
	consumerTag := queue + "-consumer"
	deliveries, err := channel.Consume(
		queue,       // name
		consumerTag, // consumerTag
		false,       // noAck
		false,       // exclusive
		false,       // noLocal
		false,       // noWait
		nil,         // arguments
	)
	if err != nil {
		panic(err)
	}
	defer channel.Cancel(consumerTag, false)

	for delivery := range deliveries {
		notif := &protobuf.Notification{}
		proto.Unmarshal(delivery.Body, notif)

		outChannel <- notif

		if err := delivery.Ack(false); err != nil {
			panic(err)
		}
	}
}
开发者ID:marchant,项目名称:RabbitMQGoDemo,代码行数:35,代码来源:consumer.go


示例11: connect

func connect(conn *amqp.Connection, exchange string, wg *sync.WaitGroup) {
	ch, err := conn.Channel()
	utils.FailOnError(err, "Failed to open a channel")
	defer conn.Close()

	err = ch.ExchangeDeclare(
		exchange, // name
		"direct", // type
		true,     // durable
		false,    // auto-deleted
		false,    // internal
		false,    // no-wait
		nil,      // arguments
	)
	utils.FailOnError(err, "Failed to declare an exchange")

	keys := []string{"create", "update"}
	for {
		for _, key := range keys {
			go connectKey(ch, key, exchange)
		}
		log.Printf("Break \n \n")
		time.Sleep(40 * time.Second)
	}
}
开发者ID:SolarCity,项目名称:ftb_timelineservice,代码行数:25,代码来源:send.go


示例12: Log

func Log(connection *amqp.Connection, inChannel chan *protobuf.Log) {
	// create a channel on this connection
	channel, err := connection.Channel()
	if err != nil {
		panic(err)
	}
	defer channel.Close()

	for log := range inChannel {
		body, err := proto.Marshal(log)
		if err != nil {
			panic(err)
		}

		err = channel.Publish(
			exchange,   // publish to an exchange
			routingKey, // routing to 0 or more queues
			false,      // mandatory
			false,      // immediate
			amqp.Publishing{
				Headers:         amqp.Table{},
				ContentType:     "",
				ContentEncoding: "",
				Body:            body,
				DeliveryMode:    amqp.Transient, // 1=non-persistent, 2=persistent
				Priority:        0,              // 0-9
				// a bunch of application/implementation-specific fields
			},
		)
		if err != nil {
			panic(err)
		}
	}
}
开发者ID:marchant,项目名称:RabbitMQGoDemo,代码行数:34,代码来源:logger.go


示例13: receive

func receive(conn *amqp.Connection, exchange string, key string, wg *sync.WaitGroup) {
	ch, err := conn.Channel()
	utils.FailOnError(err, "Failed to open a channel")
	defer ch.Close()

	err = ch.ExchangeDeclare(
		exchange, // name
		"direct", // type
		true,     // durable
		false,    // auto-deleted
		false,    // internal
		false,    // no-wait
		nil,      // arguments
	)
	utils.FailOnError(err, "Failed to declare an exchange")

	q, err := ch.QueueDeclare(
		"",    // name
		false, // durable
		false, // delete when usused
		true,  // exclusive
		false, // no-wait
		nil,   // arguments
	)
	utils.FailOnError(err, "Failed to declare a queue")

	err = ch.QueueBind(
		q.Name,   // queue name
		key,      // routing key
		exchange, // exchange
		false,
		nil)
	utils.FailOnError(err, "Failed to bind a queue")

	msgs, err := ch.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	utils.FailOnError(err, "Failed to register a consumer")

	forever := make(chan bool)

	go func() {
		for msg := range msgs {
			log.Printf(" [i] %s", key)
			go processMessage(msg.Body)
		}
	}()

	log.Printf(" [*] Waiting for logs. To exit press CTRL+C")
	<-forever
}
开发者ID:SolarCity,项目名称:ftb_timelineservice,代码行数:57,代码来源:receive.go


示例14: shutdown

// shutdown is a general closer function for handling close gracefully
// Mostly here for both consumers and producers
// After a reconnection scenerio we are gonna call shutdown before connection
func shutdown(conn *amqp.Connection) error {
	if err := conn.Close(); err != nil {
		if amqpError, isAmqpError := err.(*amqp.Error); isAmqpError && amqpError.Code != 504 {
			return fmt.Errorf("AMQP connection close error: %s", err)
		}
	}

	return nil
}
开发者ID:yuvista,项目名称:rabbitmq,代码行数:12,代码来源:rabbitmq.go


示例15: OpenChannel

/**
 * Retrieves a channel from the given connection, ConnectionDefinition
 */
func OpenChannel(connection *amqp.Connection, cd ConnectionDefinition) error {
	channel, err := connection.Channel()
	if err != nil {
		return err
	}

	Channel[cd.Vhost] = channel
	return nil
}
开发者ID:weebly-os-org,项目名称:Hare,代码行数:12,代码来源:connection.go


示例16: amqpErrorWatcher

func (i *CLI) amqpErrorWatcher(amqpConn *amqp.Connection) {
	errChan := make(chan *amqp.Error)
	errChan = amqpConn.NotifyClose(errChan)

	err, ok := <-errChan
	if ok {
		i.logger.WithField("err", err).Error("amqp connection errored, terminating")
		i.cancel()
	}
}
开发者ID:apjanke,项目名称:worker,代码行数:10,代码来源:cli.go


示例17: CreateChannel

// CreateChannel is a wrapper to simplify creating a channel with its attendant
// exchange.
func CreateChannel(conn *amqp.Connection, exchange, exchangeType string) (*amqp.Channel, error) {
	ch, err := conn.Channel()
	if err != nil {
		return nil, err
	}

	if err = ch.ExchangeDeclare(exchange, exchangeType, true, false, false, false, nil); err != nil {
		return nil, err
	}
	return ch, nil
}
开发者ID:splaspood,项目名称:raintank-metric,代码行数:13,代码来源:qproc.go


示例18: close

// Closes the connection
func (amqpBackend *AMQPBackend) close(channel *amqp.Channel, conn *amqp.Connection) error {
	if err := channel.Close(); err != nil {
		return fmt.Errorf("Channel Close: %s", err)
	}

	if err := conn.Close(); err != nil {
		return fmt.Errorf("Connection Close: %s", err)
	}

	return nil
}
开发者ID:johnkewforks,项目名称:machinery,代码行数:12,代码来源:amqp.go


示例19: Publish

func Publish(messages chan *amqp.Publishing, connectionUri, exchange,
	routingKey string, mandatory, immediate bool, results chan *PublishResult) {

	var err error
	var conn *amqp.Connection
	var channel *amqp.Channel

	defer close(results)

	if conn, err = amqp.Dial(connectionUri); err != nil {
		results <- &PublishResult{"Failed to connect", err, true}
		return
	}

	defer conn.Close()

	if channel, err = conn.Channel(); err != nil {
		results <- &PublishResult{"Failed to get channel", err, true}
		return
	}

	pubAcks, pubNacks := channel.NotifyConfirm(make(chan uint64), make(chan uint64))
	chanClose := channel.NotifyClose(make(chan *amqp.Error))
	if err = channel.Confirm(false); err != nil {
		results <- &PublishResult{
			"Failed to put channel into confirm mode",
			err,
			true,
		}
		return
	}

	for message := range messages {
		err = channel.Publish(exchange, routingKey, mandatory, immediate, *message)
		if err != nil {
			results <- &PublishResult{"Failed to publish message", err, false}
			continue
		}

		select {
		case err = <-chanClose:
			results <- &PublishResult{"Channel closed!", err, true}
		case <-pubAcks:
			results <- &PublishResult{
				fmt.Sprintf("Published to exchange '%s' routing key '%v': %+v", exchange, routingKey, message),
				nil,
				false,
			}
		case <-pubNacks:
			results <- &PublishResult{"Received basic.nack for message", errors.New("'basic.nack'"), false}
		}
	}
}
开发者ID:modcloth,项目名称:amqp-tools,代码行数:53,代码来源:publishing.go


示例20: Fire

// Fire is called when an event should be sent to the message broker.k
func (q amqpConn) Fire(entry *logrus.Entry) error {
	ch, err := q.Connection.Channel()
	if err != nil {
		// Any other error other than connection closed, return.
		if err != amqp.ErrClosed {
			return err
		}
		// Attempt to connect again.
		var conn *amqp.Connection
		conn, err = amqp.Dial(q.params.URL)
		if err != nil {
			return err
		}
		ch, err = conn.Channel()
		if err != nil {
			return err
		}
	}
	defer ch.Close()

	err = ch.ExchangeDeclare(
		q.params.Exchange,
		q.params.ExchangeType,
		q.params.Durable,
		q.params.AutoDeleted,
		q.params.Internal,
		q.params.NoWait,
		nil,
	)
	if err != nil {
		return err
	}

	body, err := entry.String()
	if err != nil {
		return err
	}

	err = ch.Publish(
		q.params.Exchange,
		q.params.RoutingKey,
		q.params.Mandatory,
		q.params.Immediate,
		amqp.Publishing{
			ContentType: "application/json",
			Body:        []byte(body),
		})
	if err != nil {
		return err
	}

	return nil
}
开发者ID:hackintoshrao,项目名称:minio,代码行数:54,代码来源:notify-amqp.go



注:本文中的github.com/streadway/amqp.Connection类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang amqp.Delivery类代码示例发布时间:2022-05-28
下一篇:
Golang amqp.Config类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap