我是 Websockets 新手。我一直在尝试使用 SimpUserRegistry 来查找主体的会话对象。我编写了一个自定义握手处理程序,将匿名用户转换为经过身份验证的用户,并且我能够从 Websocket 会话对象访问主体名称。
自定义握手处理程序的代码如下所示
import java.security.Principal;
public class StompPrincipal implements Principal {
private String name;
public StompPrincipal(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
Handler
class CustomHandshakeHandlerTwo extends DefaultHandshakeHandler {
// Custom class for storing principal
@Override
protected Principal determineUser(
ServerHttpRequest request,
WebSocketHandler wsHandler,
Map<String, Object> attributes
) {
// Generate principal with UUID as name
return new StompPrincipal(UUID.randomUUID().toString());
}
}
但正如许多问题中所指定的那样this https://stackoverflow.com/questions/32211170/spring-4-2-0-how-to-use-simpuserregistry我无法注入SimpUserRegistry
直接地。
它抛出错误
Field simpUserRegistry required a bean of type 'org.springframework.messaging.simp.user.SimpUserRegistry' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.messaging.simp.user.SimpUserRegistry' in your configuration.
所以我创建了一个配置类,如下所示。
@Configuration
public class UsersConfig {
final private SimpUserRegistry userRegistry = new DefaultSimpUserRegistry();
@Bean
@Primary
public SimpUserRegistry userRegistry() {
return userRegistry;
}
}
现在我可以自动连接并使用它,但每次我尝试访问SimpUserRegistry
它是空的。
造成这个问题的原因可能是什么?
EDIT:
显示 websocket 配置
@Configuration
@EnableWebSocket
@Controller
@Slf4j
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
EventTextHandler2 handler;
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
log.info("Registering websocket handler SocketTextHandler");
registry.addHandler(handler, "/event").setHandshakeHandler(new CustomHandshakeHandlerTwo());
}
}