Reputation: 712
I have created a new spring application which will push messages to a rabbitmq server. My rabbitMQConfig java file looks like this :
@Configuration
public class RabbitMQConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQConfig.class);
@Value("${spring.rabbitmq.host}")
private String SPRING_RABBITMQ_HOST;
@Value("${spring.rabbitmq.port}")
private int SPRING_RABBITMQ_PORT;
@Value("${spring.rabbitmq.username}")
private String SPRING_RABBITMQ_USERNAME;
@Value("${spring.rabbitmq.password}")
private String SPRING_RABBITMQ_PASSWORD;
@Bean
public RabbitTemplate rabbitTemplate(){
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(SPRING_RABBITMQ_HOST,SPRING_RABBITMQ_PORT);
connectionFactory.setUsername(SPRING_RABBITMQ_USERNAME);
connectionFactory.setPassword(SPRING_RABBITMQ_PASSWORD);
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setExchange("my.controller.exchange");
rabbitTemplate.setRoutingKey("my.controller.key");
return rabbitTemplate;
}
@Bean
DirectExchange exchange() {
return new DirectExchange("my.controller.exchange", true, false);
}
@Bean
public Queue queue() {
return new Queue("my.controller", true);
}
@Bean
Binding exchangeBinding(DirectExchange exchange, Queue queue) {
return BindingBuilder.bind(queue).to(exchange).with("my.controller.key");
}
}
Here is how I push message to the queue :
@Service
public class RabbitPublisher {
@Autowired
private RabbitTemplate rabbitTemplate;
private static Logger LOGGER = Logger.getLogger(RabbitPublisher.class);
public Boolean pushToMyQueue(HashMap<String, Object> message) {
try {
rabbitTemplate.convertAndSend("my.controller.exchange","my.controller.key",message);
return true;
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Error in pushing to my queue", e);
}
return false;
}
}
Since the exchange and queue are non-existent on the rabbitmq server, I expect them to be created automatically and message to be pushed. But it results in the following error :
ERROR 18198 --- [168.201.18:5672] o.s.a.r.c.CachingConnectionFactory :
Channel shutdown: channel error; protocol method: #method<channel.close>
(reply-code=404, reply-text=NOT_FOUND - no exchange
'my.controller.exchange' in vhost '/', class-id=60, method-id=40)
When I create the exchange and queue and bind them manually on the server, a message gets pushed successfully. Please let me know if I am missing something. Thanks.
Upvotes: 5
Views: 17931
Reputation: 455
You have to add AmqpAdmin admin bean with your required connection factory as below:
@Bean(name = "pimAmqpAdmin")
public AmqpAdmin pimAmqpAdmin(@Qualifier("defaultConnectionFactory") ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
Upvotes: 3
Reputation: 174739
You need to add a RabbitAdmin @Bean. The admin will declare the elements when a connection is first opened.
Upvotes: 5