Jay*_*mar 3 java rabbitmq spring-rabbit spring-amqp
我创建了一个新的 spring 应用程序,它将消息推送到 rabbitmq 服务器。我的 rabbitMQConfig java 文件如下所示:
@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");
}
}
Run Code Online (Sandbox Code Playgroud)
这是我将消息推送到队列的方式:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
由于rabbitmq服务器上不存在交换和队列,我希望它们会被自动创建并推送消息。但它导致以下错误:
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)
Run Code Online (Sandbox Code Playgroud)
当我创建交换和队列并在服务器上手动绑定它们时,消息被成功推送。如果我遗漏了什么,请告诉我。谢谢。
| 归档时间: |
|
| 查看次数: |
7021 次 |
| 最近记录: |