初始化bean(二)—— 缓存部分

简介: 上一篇博客,讲了下spring如何初始化bean的 当然,当时只讨论了很简单的一种情况:初次加载bean时候,并且只考虑了单例。这篇博客会试着理清楚spring在加载bean的时候的一部分缓存。

上一篇博客,讲了下spring如何初始化bean的 当然,当时只讨论了很简单的一种情况:初次加载bean时候,并且只考虑了单例。

这篇博客会试着理清楚spring在加载bean的时候的一部分缓存。关于解决循环引用所使用的缓存,可以看这篇博客

从doGetBean开始

首先再次回到doGetBean方法

上一篇博客里,我对doGetBean进行了简化,省略了很多多例及第二次加载相关的代码。

现在想下,如果让我们业务上使用缓存会怎么做。
1)先从缓存查下有没有所需数据
2)没有的话从db加载
3)加载后存到缓存里

缓存的用法无非是这样。spring也是这样使用的。

getSingleton方法

现在再来回顾getSingleton方法就很清楚了

这里我会把流程再简化下,去掉那些扩展的,异常处理等

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
    Assert.notNull(beanName, "'beanName' must not be null");
    synchronized (this.singletonObjects) {
        //先试着从缓存中加载
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null) {
            
            //异常检查 ... 
            //...
            beforeSingletonCreation(beanName);
            boolean newSingleton = false;
            //异常记录...
            try {
                //调用ObjectFactory的getObject生成这个对象
                singletonObject = singletonFactory.getObject();
                newSingleton = true;
            }
            // 省略了异常处理
            finally{
                  //....
                  afterSingletonCreation(beanName);
            }

            if (newSingleton) {
                //添加到缓存里
                addSingleton(beanName, singletonObject);
            }
        }
        return (singletonObject != NULL_OBJECT ? singletonObject : null);
    }
}

这样看就非常清楚了
1)从singleObjects试着找下对应的对象
2)从singletonFactory里创建对象
3)添加到缓存中

和我们平常使用缓存的方式没有任何不同

addSingleton记录缓存

看doGetBean方法,让我感到很晕的地方就是,各种各样缓存。(好多hashMap)而addSingleton方法就是操作缓存的一部分入口。

protected void addSingleton(String beanName, Object singletonObject) {
    synchronized (this.singletonObjects) {
        this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
        this.singletonFactories.remove(beanName);
        this.earlySingletonObjects.remove(beanName);
        this.registeredSingletons.add(beanName);
    }
}

这里我们先挑看得懂的来分析。

Map<String, Object> singletonObjects 存放了 beanName -> 创建出来的对象
Set<String> registeredSingletons 存放了已注册的单例对象

好像就这两个看得懂哦(~ ̄▽ ̄)~ 没事我们继续分析下去

回到doGetBean开头

protected <T> T doGetBean(
            final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
            throws BeansException {

        final String beanName = transformedBeanName(name);
        Object bean;

        Object sharedInstance = getSingleton(beanName);
        //.....
}

doGetBean一开始就试图通过getSingleton方法获取对应的bean
我们再回头看下getSinglteton方法

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    //已创建的对象里面找下
    Object singletonObject = this.singletonObjects.get(beanName);
    //没找到,并且当前类正在被创建
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
        synchronized (this.singletonObjects) {
            singletonObject = this.earlySingletonObjects.get(beanName);
            if (singletonObject == null && allowEarlyReference) {
                ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                if (singletonFactory != null) {
                    singletonObject = singletonFactory.getObject();
                    this.earlySingletonObjects.put(beanName, singletonObject);
                    this.singletonFactories.remove(beanName);
                }
            }
        }
    }
    return (singletonObject != NULL_OBJECT ? singletonObject : null);
}

第一行很熟悉,从已加载的对象的缓存里找下。
第二行判断,从方法名很容易猜到意思。只有当从缓存里找不到,并且当前类正在被创建才会走到里面的逻辑。

看下isSingletonCurrentlyInCreation方法

public boolean isSingletonCurrentlyInCreation(String beanName) {
    return this.singletonsCurrentlyInCreation.contains(beanName);
}

这里又出现了一个不认识的缓存 = =

Set<String> singletonsCurrentlyInCreation

从变量名,很容易猜到是记录当前单例是否正在被创建。

我们跟下往这个set里添加 值的地方。插入值的地方就在getSingleton里的beforeSingletonCreation 这一步里。
之前分析getSingleton方法时,我关注的是如何创建bean,如何使用singletonObjects缓存的。
其实在创建bean前,与创建bean后,有两个方法用于做些前置以及后置处理。分别是beforeSingletonCreationafterSingletonCreation方法。

我们看下这两个方法里都做了啥

创建bean的前置与后置处理

protected void beforeSingletonCreation(String beanName) {
    if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
        throw new BeanCurrentlyInCreationException(beanName);
    }
}

protected void afterSingletonCreation(String beanName) {
    if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
        throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
    }
}

这里又出现了两个缓存 inCreationCheckExclusionssingletonsCurrentlyInCreation

inCreationCheckExclusions这个我们先不管,到了这里singletonsCurrentlyInCreation就很清楚了,spring会在创建一个单例对象之前,记录到singletonsCurrentlyInCreation里,在创建完后,从singletonsCurrentlyInCreation里删除。

Set<String> singletonsCurrentlyInCreation 当前正在创建的beanName

回到getSingleton方法

if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {

到了这里我有几个问题:
1)为啥getSingleton方法里要进行这样的判断?
2)一般来说我们使用spring时候,都是单线程的。那么按照这个代码,创建之前添加进去,添加之后删除。那么岂不是永远不会走到这个if条件里?这些问题先记着,等分析依赖注入时候再回过头来解决。

总结

到了这里,还是有很多不知道有什么用的缓存。这些缓存会在研究依赖注入以及循环引用时候继续分析。

目录
相关文章
|
4月前
|
缓存 Java 测试技术
Spring5源码(19)-Spring从缓存中获取单例bean
Spring5源码(19)-Spring从缓存中获取单例bean
23 0
|
缓存 前端开发
ehcache jgroups同步,节点重启初始化缓存bug
ehcache jgroups同步,节点重启初始化缓存bug
115 0
|
存储 缓存 安全
|
存储 缓存 Java
分享个 之前写好的 android 文件流缓存类,专门处理 ArrayList、bean。
转载麻烦声明出处:http://www.cnblogs.com/linguanh/ 目录:   1,前序       2,作用    3,特点        4,代码     1,前序    在开发过程中,client 和 server 数据交流一般用到 json 格式传输数据。
1131 0
|
存储 缓存 Java
spring bean加载--从缓存中获取bean
标签:spring源码学习 入口方法:getSingleton,在 Object sharedInstance = getSingleton(beanName); @Override public Object getSingleton(String beanName) { return getSingleton(beanName, tr
2748 0
|
3天前
|
消息中间件 缓存 NoSQL
Redis经典问题:缓存雪崩
本文介绍了Redis缓存雪崩问题及其解决方案。缓存雪崩是指大量缓存同一时间失效,导致请求涌入数据库,可能造成系统崩溃。解决方法包括:1) 使用Redis主从复制和哨兵机制提高高可用性;2) 结合本地ehcache缓存和Hystrix限流降级策略;3) 设置随机过期时间避免同一时刻大量缓存失效;4) 使用缓存标记策略,在标记失效时更新数据缓存;5) 实施多级缓存策略,如一级缓存失效时由二级缓存更新;6) 通过第三方插件如RocketMQ自动更新缓存。这些策略有助于保障系统的稳定运行。
97 1
|
6天前
|
存储 消息中间件 缓存
Redis缓存技术详解
【5月更文挑战第6天】Redis是一款高性能内存数据结构存储系统,常用于缓存、消息队列、分布式锁等场景。其特点包括速度快(全内存存储)、丰富数据类型、持久化、发布/订阅、主从复制和分布式锁。优化策略包括选择合适数据类型、设置过期时间、使用Pipeline、开启持久化、监控调优及使用集群。通过这些手段,Redis能为系统提供高效稳定的服务。
|
11天前
|
存储 缓存 NoSQL
【Go语言专栏】Go语言中的Redis操作与缓存应用
【4月更文挑战第30天】本文探讨了在Go语言中使用Redis进行操作和缓存应用的方法。文章介绍了Redis作为高性能键值存储系统,用于提升应用性能。推荐使用`go-redis/redis`库,示例代码展示了连接、设置、获取和删除键值对的基本操作。文章还详细阐述了缓存应用的步骤及常见缓存策略,包括缓存穿透、缓存击穿和缓存雪崩的解决方案。利用Redis和合适策略可有效优化应用性能。
|
14天前
|
存储 缓存 NoSQL
Redis多级缓存指南:从前端到后端全方位优化!
本文探讨了现代互联网应用中,多级缓存的重要性,特别是Redis在缓存中间件的角色。多级缓存能提升数据访问速度、系统稳定性和可扩展性,减少数据库压力,并允许灵活的缓存策略。浏览器本地内存缓存和磁盘缓存分别优化了短期数据和静态资源的存储,而服务端本地内存缓存和网络内存缓存(如Redis)则提供了高速访问和分布式系统的解决方案。服务器本地磁盘缓存因I/O性能瓶颈和复杂管理而不推荐用于缓存,强调了内存和网络缓存的优越性。
40 1
|
1天前
|
缓存 NoSQL 应用服务中间件
Redis多级缓存
Redis多级缓存
8 0