首先要理解EmbeddedServletContainerAutoConfiguration 配置的过程
请查看
https://blog.csdn.net/l18767118724/article/details/83589173
这里就是要加深对 WebSocketContainerCustomizer这个类的认识。
这个类会在 org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory#configureContext方法被调用前使用。根据这个流程,可以使用EmbeddedServletContainerAutoConfiguration中的创建的TomcatEmbeddedServletContainerFactory对象进行有效的操作。如下是修改session管理器。tomcat默认的是StandardManager
现在自定义自己的LightSessionManager。这个管理器不校验session,不持久化,只是生成。
@Configuration
@AutoConfigureAfter(EmbeddedServletContainerAutoConfiguration.class)
public class SessionManagerConfiguration {
@Bean
public SessionManagerCustomizer sessionManagerCustomizer() {
return new SessionManagerCustomizer();
}
class SessionManagerCustomizer extends WebSocketContainerCustomizer<TomcatEmbeddedServletContainerFactory> {
@Override
protected void doCustomize(TomcatEmbeddedServletContainerFactory container) {
container.addContextCustomizers(new TomcatContextCustomizer() {
@Override
public void customize(Context context) {
context.setManager(new LightSessionManager());
}
});
}
}
/**
* 重写session管理,不持久。如果没有则生成一个session。后面通过redis校验session是否有效。
*/
class LightSessionManager extends ManagerBase {
@Override
public Session findSession(String id) throws IOException {
Session session = super.findSession(id);
if (Objects.isNull(session)) {
session = super.createSession(id);
}
return session;
}
@Override
public void load() {
}
@Override
public void unload() {
}
@Override
protected void startInternal() throws LifecycleException {
super.startInternal();
this.setState(LifecycleState.STARTING);
}
@Override
protected void stopInternal() throws LifecycleException {
this.setState(LifecycleState.STOPPING);
super.stopInternal();
}
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章