示例#1
0
文件: amqp.go 项目: gooops/machinery
// Publish places a new message on the default queue
func (amqpBroker *AMQPBroker) Publish(signature *signatures.TaskSignature) error {
	conn, channel, _, confirmsChan, err := amqpBroker.open()
	if err != nil {
		return err
	}

	defer amqpBroker.close(channel, conn)

	message, err := json.Marshal(signature)
	if err != nil {
		return fmt.Errorf("JSON Encode Message: %v", err)
	}

	signature.AdjustRoutingKey(
		amqpBroker.config.ExchangeType,
		amqpBroker.config.BindingKey,
		amqpBroker.config.DefaultQueue,
	)
	if err := channel.Publish(
		amqpBroker.config.Exchange, // exchange
		signature.RoutingKey,       // routing key
		false,                      // mandatory
		false,                      // immediate
		amqp.Publishing{
			Headers:      amqp.Table(signature.Headers),
			ContentType:  "application/json",
			Body:         message,
			DeliveryMode: amqp.Persistent,
		},
	); err != nil {
		return err
	}

	confirmed := <-confirmsChan

	if confirmed.Ack {
		return nil
	}

	return fmt.Errorf("Failed delivery of delivery tag: %v", confirmed.DeliveryTag)
}
示例#2
0
func TestAdjustRoutingKey(t *testing.T) {
	var signature signatures.TaskSignature

	signature = signatures.TaskSignature{
		RoutingKey: "routing_key",
	}
	signature.AdjustRoutingKey("direct", "binding_key", "queue")

	assert.Equal(t, "routing_key", signature.RoutingKey)

	signature = signatures.TaskSignature{
		RoutingKey: "",
	}
	signature.AdjustRoutingKey("direct", "binding_key", "queue")

	assert.Equal(t, "binding_key", signature.RoutingKey)

	signature = signatures.TaskSignature{
		RoutingKey: "",
	}
	signature.AdjustRoutingKey("topic", "binding_key", "queue")

	assert.Equal(t, "queue", signature.RoutingKey)
}