简体   繁体   English

Spring Boot Rabbitmq AMQP & WebSocket NULL 指针异常

[英]Spring Boot Rabbitmq AMQP & WebSocket NULL pointer exception

I'm trying to send a message with a Rabbitmq in WebSocketHandler, right after the user's connection establishes.我正在尝试在用户连接建立后立即在 WebSocketHandler 中使用 Rabbitmq 发送消息。 The problem is, that the Rabbitmq producer bean is null.问题是,Rabbitmq 生产者 bean 为空。 Calling a producer from the Controller works perfectly fine, but when i try to call it from the WebSocketHandler bean, if fails with NULL pointer exception:从控制器调用生产者工作得很好,但是当我尝试从 WebSocketHandler bean 调用它时,如果失败并出现 NULL 指针异常:

WebSocket configuration: WebSocket 配置:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {


public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(new MyWebSocketHandler(), "/connect");
}

}

WebSocket handler bean, where the NULL pointer exceptions heppens: WebSocket 处理程序 bean,其中出现 NULL 指针异常:

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
private static final Logger LOG = LoggerFactory.getLogger(WebSocketConfig.class);

@Autowired
QueueProducer producer; //NULL

List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    sessions.add(session);
    List<String> lol = session.getHandshakeHeaders().get("User-Agent");
    //Calling the rabbitmq producer
    producer.produce("Hi Mark");//NULL
}

Rabbitmq config: RabbitMQ 配置:

@Configuration
public class RabbitConfiguration {

@Value("${fanout.exchange}")
private String fanoutExchange;

@Value("${queue.name}")
private String queueName;

@Bean
Queue queue() {
return new Queue(queueName, true);
}

@Bean
FanoutExchange exchange() {
return new FanoutExchange(fanoutExchange);
}

@Bean
Binding binding(Queue queue, FanoutExchange exchange) {
return BindingBuilder.bind(queue).to(exchange);
}

}

Rabbitmq producer code: Rabbitmq 生产者代码:

@Component
public class QueueProducer {

protected Logger logger = LoggerFactory.getLogger(getClass());

@Value("${fanout.exchange}")
private String fanoutExchange;

private final RabbitTemplate rabbitTemplate;

@Autowired
public QueueProducer(RabbitTemplate rabbitTemplate) {
    super();
    this.rabbitTemplate = rabbitTemplate;
}

public void produce(String message) throws Exception {
    logger.info("Storing notification...");
    rabbitTemplate.setExchange(fanoutExchange);
    rabbitTemplate.convertAndSend(message);
    logger.info("Notification stored in queue sucessfully");
}

}

Stack Trace:堆栈跟踪:

java.lang.NullPointerException: null
at com.ta9.common.Config.MyWebSocketHandler.afterConnectionEstablished(MyWebSocketHandler.java:43) ~[classes/:na]
at org.springframework.web.socket.handler.WebSocketHandlerDecorator.afterConnectionEstablished(WebSocketHandlerDecorator.java:70) ~[spring-websocket-5.3.8.jar:5.3.8]
at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.afterConnectionEstablished(LoggingWebSocketHandlerDecorator.java:48) ~[spring-websocket-5.3.8.jar:5.3.8]
at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.afterConnectionEstablished(ExceptionWebSocketHandlerDecorator.java:48) ~[spring-websocket-5.3.8.jar:5.3.8]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.onOpen(StandardWebSocketHandlerAdapter.java:104) ~[spring-websocket-5.3.8.jar:5.3.8]
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.init(WsHttpUpgradeHandler.java:135) ~[tomcat-embed-websocket-9.0.48.jar:9.0.48]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:940) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

Thank you in advance.先感谢您。

That's expected behavior.这是预期的行为。 Let's see to your code one more time:让我们再看看你的代码:

registry.addHandler(new MyWebSocketHandler(), "/connect");

You see you do new manually.你会看到你手动做new You don't rely on dependency injection container over here.你不依赖这里的依赖注入容器。 Your MyWebSocketHandler is not a bean in this case.在这种情况下,您的MyWebSocketHandler不是 bean。 Since it is marked as a @Component I suppose it is scanned properly and made it available as a bean into an application context.由于它被标记为@Component我想它被正确扫描并使其作为 bean 可用于应用程序上下文。 So, probably you can do like this to fix your problem:所以,也许你可以这样做来解决你的问题:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    MyWebSocketHandler myWebSocketHandler;
   
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(this.myWebSocketHandler, "/connect");
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM