// BrokerFactory creates a new object with brokers.Broker interface // Currently only AMQP broker is supported func BrokerFactory(cnf *config.Config) (brokers.Broker, error) { if strings.HasPrefix(cnf.Broker, "amqp://") { return brokers.NewAMQPBroker(cnf), nil } if strings.HasPrefix(cnf.Broker, "redis://") { parts := strings.Split(cnf.Broker, "redis://") if len(parts) != 2 { return nil, fmt.Errorf( "Redis broker connection string should be in format redis://host:port, instead got %s", cnf.Broker, ) } redisHost, redisPassword, redisDB, err := ParseRedisURL(cnf.Broker) if err != nil { return nil, err } return brokers.NewRedisBroker(cnf, redisHost, redisPassword, "", redisDB), nil } if strings.HasPrefix(cnf.Broker, "redis+socket://") { redisSocket, redisPassword, redisDB, err := ParseRedisSocketURL(cnf.Broker) if err != nil { return nil, err } return brokers.NewRedisBroker(cnf, "", redisPassword, redisSocket, redisDB), nil } if strings.HasPrefix(cnf.Broker, "eager") { return brokers.NewEagerBroker(), nil } return nil, fmt.Errorf("Factory failed with broker URL: %v", cnf.Broker) }
func TestBrokerFactory(t *testing.T) { var cnf config.Config // 1) AMQP broker test cnf = config.Config{ Broker: "amqp://*****:*****@localhost:5672/", Exchange: "machinery_exchange", ExchangeType: "direct", DefaultQueue: "machinery_tasks", BindingKey: "machinery_task", } actual, err := machinery.BrokerFactory(&cnf) if assert.NoError(t, err) { expected := brokers.NewAMQPBroker(&cnf) assert.True( t, reflect.DeepEqual(actual, expected), fmt.Sprintf("conn = %v, want %v", actual, expected), ) } // 1) Redis broker test // with password cnf = config.Config{ Broker: "redis://password@localhost:6379", DefaultQueue: "machinery_tasks", } actual, err = machinery.BrokerFactory(&cnf) if assert.NoError(t, err) { expected := brokers.NewRedisBroker(&cnf, "localhost:6379", "password", "", 0) assert.True( t, reflect.DeepEqual(actual, expected), fmt.Sprintf("conn = %v, want %v", actual, expected), ) } // without password cnf = config.Config{ Broker: "redis://localhost:6379", DefaultQueue: "machinery_tasks", } actual, err = machinery.BrokerFactory(&cnf) if assert.NoError(t, err) { expected := brokers.NewRedisBroker(&cnf, "localhost:6379", "", "", 0) assert.True( t, reflect.DeepEqual(actual, expected), fmt.Sprintf("conn = %v, want %v", actual, expected), ) } // using a socket file cnf = config.Config{ Broker: "redis+socket:///tmp/redis.sock", DefaultQueue: "machinery_tasks", } actual, err = machinery.BrokerFactory(&cnf) if assert.NoError(t, err) { expected := brokers.NewRedisBroker(&cnf, "", "", "/tmp/redis.sock", 0) assert.True( t, reflect.DeepEqual(actual, expected), fmt.Sprintf("conn = %v, want %v, actual, expected"), ) } }