gpt4 book ai didi

java - Spring Websocket getServerName 服务中

转载 作者:太空宇宙 更新时间:2023-11-04 13:11:54 25 4
gpt4 key购买 nike

我正在我的 Spring 应用程序中实现路由数据源。获取查找 key 的方法之一是访问 HttpServletRequest 并通过调用方法获取当前域作为 key

request.getServerName()

HttpServletRequest 通过 RequestContextHolder 访问,如下

(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()

或者只是通过 Autowiring HttpServletRequest

@Autowired
private HttpServletRequest request;

当我在请求范围内时,使用 Controller 中的标准 @RequestMapping 注释,一切正常。我想在 @MessageMapping 注释的 WebSocket 方法中做同样的事情。没有请求范围,因此 Autowiring HttpServletRequest 并调用方法 getServerName() 会出现如下异常

No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

消息使用 Stomp 和 SockJs 传递到 Controller 。这是我的配置

 @Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/sub");
config.setApplicationDestinationPrefixes("/some");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}

和 Controller

@Autowired
private SomeService service;

@MessageMapping("/someUrl/{param}")
public void subscribeForMessage(@DestinationVariable Long param) {
service.doSmth();
}

我不想将它从 Controller 传递到服务,因为调用链更长,并且获取当前查找 key 必须是透明的。是否可以通过类似于 Autowiring HttpServletRequest 的方式获取服务器名称?是否可以注入(inject) websocket 请求或 session 的某些“范围”而不传递它?

最佳答案

您必须初始化RequestContextListener的bean来请求除@Controller(请求范围)之外的对象。

    @Bean
public RequestContextListener requestContextListener() {
return new RequestContextListener();
}

关于java - Spring Websocket getServerName 服务中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33874853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com