springboot2如何禁用自带tomcat的session功能

 更新时间:2021年11月09日 14:47:31   作者:song.xl  
这篇文章主要介绍了springboot2如何禁用自带tomcat的session功能,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

禁用自带tomcat的session功能

微服务下的各个服务都是无状态的,所以这个时候tomcat的session管理功能是多余的,即时不用,也会消耗性能,关闭后tomcat的性能会有提升,但是springboot提供的tomcat没有配置选项可以直接关闭,研究了一下,tomcat默认的session管理器名字叫:StandardManager,查看tomcat加载源码发现,如果context中没有Manager的时候,直接new StandardManager(),源码片段如下:

               Manager contextManager = null;
                Manager manager = getManager();
                if (manager == null) {
                    if (log.isDebugEnabled()) {
                        log.debug(sm.getString("standardContext.cluster.noManager",
                                Boolean.valueOf((getCluster() != null)),
                                Boolean.valueOf(distributable)));
                    }
                    if ((getCluster() != null) && distributable) {
                        try {
                            contextManager = getCluster().createManager(getName());
                        } catch (Exception ex) {
                            log.error(sm.getString("standardContext.cluster.managerError"), ex);
                            ok = false;
                        }
                    } else {
                        contextManager = new StandardManager();
                    }
                }
 
                // Configure default manager if none was specified
                if (contextManager != null) {
                    if (log.isDebugEnabled()) {
                        log.debug(sm.getString("standardContext.manager",
                                contextManager.getClass().getName()));
                    }
                    setManager(contextManager);
                }

为了不让tomcat去new自己的管理器,必须让第二行的getManager()获取到对象,所以就可以从这里入手解决,我的解决办法如下:自定义一个tomcat工厂,继承原来的工厂,context中加入自己写的manager

@Component
public class TomcatServletWebServerFactorySelf extends TomcatServletWebServerFactory { 
    protected void postProcessContext(Context context) {
        context.setManager(new NoSessionManager());
    }
}
public class NoSessionManager extends ManagerBase implements Lifecycle { 
    @Override
    protected synchronized void startInternal() throws LifecycleException {
        super.startInternal();
        try {
            load();
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            t.printStackTrace();
        }
        setState(LifecycleState.STARTING);
    }
 
    @Override
    protected synchronized void stopInternal() throws LifecycleException {
        setState(LifecycleState.STOPPING);
        try {
            unload();
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            t.printStackTrace();
        }
        super.stopInternal();
    }
 
    @Override
    public void load() throws ClassNotFoundException, IOException {
        log.info("HttpSession 已经关闭,若开启请配置:seeyon.tomcat.disableSession=false");
    }
 
    @Override
    public void unload() throws IOException {}
    @Override
    public Session createSession(String sessionId) {
        return null;
    }
 
    @Override
    public Session createEmptySession() {
        return null;
    }
 
    @Override
    public void add(Session session) {}
    @Override
    public Session findSession(String id) throws IOException {
        return null;
    }
    @Override
    public Session[] findSessions(){
        return null;
    }
    @Override
    public void processExpires() {}
}

两个类解决问题,这样通过request获取session就是空了,tomcat摆脱session这层处理性能有所提升。

禁用内置Tomcat的不安全请求方法

起因:安全组针对接口测试提出的要求,需要关闭不安全的请求方法,例如put、delete等方法,防止服务端资源被恶意篡改。

用过springMvc都知道可以使用@PostMapping、@GetMapping等这种注解限定单个接口方法类型,或者是在@RequestMapping中指定method属性。这种方式比较麻烦,那么有没有比较通用的方法,通过查阅相关资料,答案是肯定的。

tomcat传统形式通过配置web.xml达到禁止不安全的http方法

    <security-constraint>  
       <web-resource-collection>  
          <url-pattern>/*</url-pattern>  
          <http-method>PUT</http-method>  
       <http-method>DELETE</http-method>  
       <http-method>HEAD</http-method>  
       <http-method>OPTIONS</http-method>  
       <http-method>TRACE</http-method>  
       </web-resource-collection>  
       <auth-constraint>  
       </auth-constraint>  
    </security-constraint>  
    <login-config>  
      <auth-method>BASIC</auth-method>  
    </login-config>

Spring boot使用内置tomcat,2.0版本以前使用如下形式

@Bean  
public EmbeddedServletContainerFactory servletContainer() {  
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {// 1  
        protected void postProcessContext(Context context) {  
            SecurityConstraint securityConstraint = new SecurityConstraint();  
            securityConstraint.setUserConstraint("CONFIDENTIAL");  
            SecurityCollection collection = new SecurityCollection();  
            collection.addPattern("/*");  
            collection.addMethod("HEAD");  
            collection.addMethod("PUT");  
            collection.addMethod("DELETE");  
            collection.addMethod("OPTIONS");  
            collection.addMethod("TRACE");  
            collection.addMethod("COPY");  
            collection.addMethod("SEARCH");  
            collection.addMethod("PROPFIND");  
            securityConstraint.addCollection(collection);  
            context.addConstraint(securityConstraint);  
        }  
    };

2.0版本使用以下形式

@Bean
public ConfigurableServletWebServerFactory configurableServletWebServerFactory() {
    TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
    factory.addContextCustomizers(context -> {
        SecurityConstraint securityConstraint = new SecurityConstraint();
        securityConstraint.setUserConstraint("CONFIDENTIAL");
        SecurityCollection collection = new SecurityCollection();
        collection.addPattern("/*");
        collection.addMethod("HEAD");
        collection.addMethod("PUT");
        collection.addMethod("DELETE");
        collection.addMethod("OPTIONS");
        collection.addMethod("TRACE");
        collection.addMethod("COPY");
        collection.addMethod("SEARCH");
        collection.addMethod("PROPFIND");
        securityConstraint.addCollection(collection);
        context.addConstraint(securityConstraint);
    });
    return factory;
}

关于内嵌tomcat的更多配置,感兴趣可以阅读官方文档

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • springboot集成Feign的实现示例

    springboot集成Feign的实现示例

    Feign是声明式HTTP客户端,用于简化微服务之间的REST调用,本文就来介绍一下springboot集成Feign的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-11-11
  • 基于IDEA中格式化代码的快捷键分享

    基于IDEA中格式化代码的快捷键分享

    这篇文章主要介绍了基于IDEA中格式化代码的快捷键分享,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • Java中Executor和Executors的区别小结

    Java中Executor和Executors的区别小结

    在Java并发编程中,Executor是一个核心接口,提供了任务执行的抽象方法,而Executors是一个工具类,提供了创建各种线程池的工厂方法,Executor关注任务的执行,而Executors关注如何创建适合的执行器,感兴趣的可以了解一下
    2024-10-10
  • selenium-java实现自动登录跳转页面方式

    selenium-java实现自动登录跳转页面方式

    利用Selenium和Java语言可以编写一个脚本自动刷新网页,首先,需要确保Google浏览器和Chrome-Driver驱动的版本一致,通过指定网站下载对应版本的浏览器和驱动,在Maven项目中添加依赖,编写脚本实现网页的自动刷新,此方法适用于需要频繁刷新网页的场景,简化了操作,提高了效率
    2024-11-11
  • 微信公众平台开发实战Java版之微信获取用户基本信息

    微信公众平台开发实战Java版之微信获取用户基本信息

    这篇文章主要介绍了微信公众平台开发实战Java版之微信获取用户基本信息 的相关资料,需要的朋友可以参考下
    2015-12-12
  • java组件commons-fileupload文件上传示例

    java组件commons-fileupload文件上传示例

    这篇文章主要为大家详细介绍了java组件commons-fileupload实现文件上传,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • SpringBoot中将@Bean方法解析为BeanDefinition详解

    SpringBoot中将@Bean方法解析为BeanDefinition详解

    这篇文章主要介绍了SpringBoot中将@Bean方法解析为BeanDefinition详解,得到的BeanDefinition是ConfigurationClassBeanDefinition类型,会为BeanDefinition设置factoryMethodName,这意味着当实例化这个bean的时候将采用工厂方法,需要的朋友可以参考下
    2023-12-12
  • SpringBoot使用AOP记录接口操作日志详解

    SpringBoot使用AOP记录接口操作日志详解

    这篇文章主要为大家详细介绍了SpringBoot使用AOP记录接口操作日志,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-08-08
  • JAVA IO的3种类型区别解析

    JAVA IO的3种类型区别解析

    这篇文章主要介绍了JAVA IO的3种类型解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • Java并发编程之常用的辅助类详解

    Java并发编程之常用的辅助类详解

    这篇文章主要给大家介绍了关于Java并发编程之常用的辅助类的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01

最新评论