RabbitMQ连接工厂未自动将消息注入或转换为JSON

fzsnzjdm  于 2022-09-19  发布在  RabbitMQ
关注(0)|答案(2)|浏览(159)

我正在为我的rabbitmq应用程序设置连接工厂。我在配置中创建了bean,但是由于某种原因,我传递到RabbitTemplate中的ConnectionFactory似乎没有自动创建bean。
错误的说法是Could not autowire. No beans of 'ConnectionFactory' type found.,但是这个bean应该自动创建。如果我手动创建了一个连接工厂的bean,它就会工作,但我很难理解为什么没有它它就不能工作。

package com.example.redistorabbit;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class RedisToRabbitApplication {

public static void main(String[] args) {
    SpringApplication.run(RedisToRabbitApplication.class, args);
}

public static final String TOPIC_EXCHANGE_NAME = "covid-exchange";
public static final String QUEUE_NAME = "cases-entity";

@Bean
Queue queue(){
    return new Queue(QUEUE_NAME,false);
}

@Bean
TopicExchange exchange(){
    return new TopicExchange(TOPIC_EXCHANGE_NAME);
}

@Bean
Binding binding(Queue queue, TopicExchange topicExchange){
    return BindingBuilder.bind(queue).to(topicExchange).with("#");
}

@Bean
public RabbitTemplate publishingRabbitTemplate(final ConnectionFactory connectionFactory) {
    final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
    rabbitTemplate.setMessageConverter(jsonConverter());
    rabbitTemplate.setChannelTransacted(true);
    return rabbitTemplate;
}

@Bean
public Jackson2JsonMessageConverter jsonConverter() {
    return new Jackson2JsonMessageConverter();
}

}

另一个问题是,即使我有Jackson2JsonMessageConverter,当lisetener接收并打印它显示为字节而不是json消息的消息时:

@Component
@RequiredArgsConstructor
public class Receiver {

private final CasesRepository casesRepository;

private static final Logger log = LoggerFactory.getLogger(Receiver.class);

@RabbitListener(queues = RedisToRabbitApplication.QUEUE_NAME)
public void consumeMessage(final Message message) {
    log.info("received: " + message.toString());
}
}

收到:(正文:'[B@1b68f46c(字节[91])

f4t66c6m

f4t66c6m1#

您是否尝试将Spring对象Map器注入Jackson消息转换器?

@Bean
public Jackson2JsonMessageConverter jsonConverter(ObjectMapper objectMapper) {
    return new Jackson2JsonMessageConverter(objectMapper);
}
ni65a41a

ni65a41a2#

似乎问题在于spring boot自动配置依赖的版本,我可以在JacksonAutoConfiguration类的2.7.3版本中看到bean,但Intellij仍然表示没有找到bean。我添加了以下依赖项:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>1.5.15.RELEASE</version>
    </dependency>

ConnectionFactory和ObjectMapper bean都是自动创建的

相关问题