Performance problems when using lots of AOP request scoped beans

前端 未结 3 571
暖寄归人
暖寄归人 2021-02-14 22:48

I\'m working on a semi-large application using Spring 3 and am running into performance problems when throwing hundreds of users at it at once. I\'m using several request scope

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-14 23:37

    Interesting question.

    It turns out that Spring's scoped proxy doesn't cache resolved objects, so that every access to the scoped proxy causes getBean() to be called.

    As a workaround, you can create a poor man's caching scoped proxy, something like this (untested, target bean should be request-scoped, but without ):

    public class MyScopedProxy implements SomeInterface, BeanFactoryAware {
    
        private BeanFactory factory;
        private Scope scope;
        private String targetBeanName;
        private ThreadLocal cache = new ThreadLocal();
    
        private SomeInterface resolve() {
            SomeInterface v = cache.get();
            if (v == null) {
                v = (SomeInterface) factory.getBean(targetBeanName);
                cache.set(v);
                scope.registerDestructionCallback(targetBeanName, new Runnable() {
                    public void run() {
                        cache.remove();
                    }
                });
            }
            return v;
        }
    
        public void setBeanFactory(BeanFactory factory) {
            this.factory = factory;
            this.scope = ((ConfigurableBeanFactory) factory).getRegisteredScope("request");
        }
    
        public String getProperty() {
            return resolve().getProperty();
        }
    
        ...
    }
    

    Regarding the proxying mechanisms: unlike other AOP proxies, scoped proxies are CGLIB by default, you can override it by setting , but it wouldn't help in this case.

提交回复
热议问题