在学习openfire的Cluster管理中,发现很多地方都涉及到对缓存的操作,尤其是分布式实现中,因此,有必要对缓存机制有个整体的了解。
Cache接口:该接口扩展了java 的Map接口,主要是加入了一些成员函数,用来返回缓存的最大尺寸,命中率,MIss率 最大生存期等特性。
Cacheable 接口:扩展了java.io.Serializable接口,提供getCachedSize方法返回缓存数据的大小
CacheSizes: 功能类,用来获取缓存对象的大小。实现了Cacheable 接口的类需要使用这个类去确定它们的大小
ExternalizableUtil 类:该类只有在节点运行于集群之中时才会用到。 采用策略模式,实际执行操作的是其内部的ExternalizableUtilStrategy 类型实例strategy。对于开源版本,strategy 的实际类型为DummyExternalizableUtil
ExternalizableUtilStrategy接口:用来实现对象的串行化,针对openfire开源版本和企业版本有不同的子类。ExternalizableUtil 类中保存有其子类实例strategy进行实际的串行化。针对开源版本,其子类实现为DummyExternalizableUtil,查看该类的定义可发现其什么也不做,只是单纯的实现了ExternalizableUtilStrategy接口。而针对企业版本openfire,则对象的串行化实际上是采用coherence来实现其底层机制。
接下来看看CacheFactory类,该类是整个缓存机制的核心,通过查看其源代码,发现此处也是采用策略模式,其真正的操作是由存储在其中的三个 类类型的变量来执行的:
private static CacheFactoryStrategy cacheFactoryStrategy = new DefaultLocalCacheStrategy();
private static CacheFactoryStrategy localCacheFactoryStrategy;
private static CacheFactoryStrategy clusteredCacheFactoryStrategy;
其中,cacheFactoryStrategy 变量 被初始化为DefaultLocalCacheStrategy类型的实例。
cacheFactoryStrategy 可以看作是本节点 默认的缓存管理类,当本节点未加入Cluster时,其值就是localCacheFactoryStrategy,当本节点加入了Cluster时,其值为clusteredCacheFactoryStrategy。
而clusteredCacheFactoryStrategy 的初始化是在isClusteringAvailable函数中中进行的:
public static boolean isClusteringAvailable() {
if (clusteredCacheFactoryStrategy == null) {
try {
clusteredCacheFactoryStrategy = (CacheFactoryStrategy) Class.forName(
clusteredCacheFactoryClass, true,
getClusteredCacheStrategyClassLoader()).newInstance();
} catch (NoClassDefFoundError e) {
log.warn("Clustered cache factory strategy " + clusteredCacheFactoryClass + " not found");
} catch (Exception e) {
log.warn("Clustered cache factory strategy " + clusteredCacheFactoryClass + " not found");
}
}
return (clusteredCacheFactoryStrategy != null);
}
可以看出,clusteredCacheFactoryStrategy 实际上被初始化为clusteredCacheFactoryClass 变量所对应的类类型。而clusteredCacheFactoryClass 的初始化是位于static代码段中:
clusteredCacheFactoryClass = JiveGlobals.getProperty(CLUSTERED_CACHE_PROPERTY_NAME,
"com.jivesoftware.util.cache.ClusteredCacheFactory");
因此,clusteredCacheFactoryStrategy 的类型实际上为com.jivesoftware.util.cache.ClusteredCacheFactory。 而在openfire自带的源码中为发现此类,故而猜测此类应定义在相应的分布式插件中。(有待验证)
localCacheFactoryStrategy的初始化方法类似于clusteredCacheFactoryStrategy ,初始化代码位于initialize函数中:
public static synchronized void initialize() throws InitializationException {
try {
localCacheFactoryStrategy = (CacheFactoryStrategy) Class.forName(localCacheFactoryClass).newInstance();
cacheFactoryStrategy = localCacheFactoryStrategy;
} catch (Exception e) {
log.error("Failed to instantiate local cache factory strategy: " + localCacheFactoryClass, e);
throw new InitializationException(e);
}
}