我的目标是使用 SimpUserRegistry 检查有多少用户订阅了某个主题,以限制订阅数量。为了测试我的代码,我使用了基本的 https://spring.io/guides/gs/messaging-stomp-websocket/ 项目。
这是我对此项目的唯一更改:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Autowired
private TopicSubscriptionInterceptor topicSubscriptionInterceptor
...
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(topicSubscriptionInterceptor);
}
}
//------------------------------------------------------------ ---------------------------------------
@Component
public class TopicSubscriptionInterceptor implements ChannelInterceptor {
@Autowired
private SimpUserRegistry userRegistry;
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel){
// ... use SimpUserRegistry to check amount of users subscribed to a topic and whether
// or not to allow a subscription (throw exception/null)
}
//------------------------------------------------------------ ------------------------------------------
我尝试只传递
new TopicSubscriptionInterceptor()
,而不是使用 @Autowired 将其添加为依赖项,但这显然会使 TopicSubscriptionInterceptor 中的所有依赖项都为空。
//------------------------------------------------------------ ----
依赖循环:
┌─────┐
| webSocketConfig (field private com.xxx.yyy.interceptor.TopicSubscriptionInterceptor com.xxx.yyy.config.WebSocketConfig.topicSubscriptionInterceptor)
↑ ↓
| topicSubscriptionInterceptor (field private org.springframework.messaging.simp.user.SimpUserRegistry com.xxx.yyy.interceptor.TopicSubscriptionInterceptor.userRegistry)
↑ ↓
| org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration
└─────┘
这是我尝试过的编辑(1):
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Bean
public TopicSubscriptionInterceptor
myTopicSubscriptionInterceptor(){
return new TopicSubscriptionInterceptor();
}
...
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(myTopicSubscriptionInterceptor());
}
}
使用延迟初始化解决了这个问题,尽管它感觉像是一个创可贴解决方案。由于我是 Spring 新手,我不确定是否还有其他更好的方法。
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
private TopicSubscriptionInterceptor topicSubscriptionInterceptor;
@Autowired
public WebSocketConfig(@Lazy TopicSubscriptionInterceptor topicSubscriptionInterceptor) {
this.topicSubscriptionInterceptor = topicSubscriptionInterceptor;
}
...
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(topicSubscriptionInterceptor);
}
}
我也有同样的问题。你的解决方案是帮助我。