---
title: "Velocity 分析"
author: "successfulroof"
date: "2013-01-21T18:43:43Z"
tags: []
categories: ["Web前端"]
slug: "velocity"
draft: false
lastmod: "2013-01-24T11:17:22Z"
id: 1773299
url: "https://fucky.iteye.com/blog/1773299"
---

Velocity是什么？这里就不做分析了！重点写一写velocity的工作机制，如果文章中哪里有问题还请各位指出，以防误人子弟

其实简单的说，velocity分两大块：

一、资源加载

         使用velocity，我们可以通过一次编写模板而达到多次复用的效果，运用起来也十分的方便，相应速度也比较理想，因为velocity本身也提供模板的缓存功能，对比每次读取文件来说也是要快很多！而且模板缓存原理也是根据文件的修改时间来判断的，如果缓存lastModified &lt; modifiedTime缓存失效，重新加载文件载入缓存！

        1.资源加载器初始化

```
//主要工作类：VelocityEngine
获取模板方法：
/**
*@param templateName 模板名称
*@param encoding 加载文件编码，默认：ISO-8859-1
**/
velocityEngine.getTemplate(templateName,encoding);
```

        主要加载VM文件类：ResourceManagerImpl ，manager初始化方法分析

    

```
 public synchronized void initialize(final RuntimeServices rsvc)
        throws Exception
    {
        if (isInit) //是否初始化，防止重入
        {
            log.debug("Re-initialization of ResourceLoader attempted and ignored.");
            return;
        }
	//资源加载器
        ResourceLoader resourceLoader = null;
       
        // runtimeService 主要用来存储加载文件的一些参数的KEY。如：加载路    径
        this.rsvc = rsvc;
        log = rsvc.getLog();

        log.trace("Default ResourceManager initializing. (" + this.getClass() + ")");
       //组装资源加载器，主要就从runtimeservice中拿出配置的加载器，
       //如果没有配置资源加载器，默认是使用 
     // org.apache.velocity.runtime.resource.loader.FileResourceLoader
       //现在是junit单元测试，使用的是：ClasspathResourceLoader
      /**加载器支持放入List，你同时可以使用多个资源加载器，
         *在一个资源加载器加载不到资源的时候，会使用下一个加载器去加载 
        * 资源加载器都会放入sourceInitializerList
        **/
        assembleResourceLoaderInitializers();
       
        for (Iterator it = sourceInitializerList.iterator(); it.hasNext();)
        {
            /**
             *
             * in as an instance.扩展属性，如：具体文件加载目录，加载器。个人
             *绝对velocity的参数设置比较繁琐，又支持多个类里面设置，容易搞混
             */
            ExtendedProperties configuration = (ExtendedProperties) it.next();
          //从配置冲获取 资源加载器
            String loaderClass = StringUtils.nullTrim(configuration.getString("class"));
            ResourceLoader loaderInstance = (ResourceLoader) configuration.get("instance");

            if (loaderInstance != null)
            {
                resourceLoader = loaderInstance;
            }
            else if (loaderClass != null)
            {
                resourceLoader = ResourceLoaderFactory.getLoader(rsvc, loaderClass);
            }
            else
            {
                String msg = "Unable to find '" +
                          configuration.getString(RESOURCE_LOADER_IDENTIFIER) +
                          ".resource.loader.class' specification in configuration." +
                          " This is a critical value.  Please adjust configuration.";
                log.error(msg);
                throw new Exception(msg);
            }

            resourceLoader.commonInit(rsvc, configuration);
            resourceLoader.init(configuration);
            resourceLoaders.add(resourceLoader);
        }

        /*
         * now see if this is overridden by configuration
         */

        logWhenFound = rsvc.getBoolean(RuntimeConstants.RESOURCE_MANAGER_LOGWHENFOUND, true);

        /*
         *  获取 资源缓存器默认ResourceCacheImpl
         */

        String cacheClassName = rsvc.getString(RuntimeConstants.RESOURCE_MANAGER_CACHE_CLASS);

        Object cacheObject = null;

        if (org.apache.commons.lang.StringUtils.isNotEmpty(cacheClassName))
        {

            try
            {
                cacheObject = ClassUtils.getNewInstance(cacheClassName);
            }
            catch (ClassNotFoundException cnfe)
            {
                String msg = "The specified class for ResourceCache (" + cacheClassName +
                          ") does not exist or is not accessible to the current classloader.";
                log.error(msg, cnfe);
                throw cnfe;
            }

            if (!(cacheObject instanceof ResourceCache))
            {
                String msg = "The specified resource cache class (" + cacheClassName +
                          ") must implement " + ResourceCache.class.getName();
                log.error(msg);
                throw new RuntimeException(msg);
            }
        }

        /*
         *  if we didn't get through that, just use the default.
         */
        if (cacheObject == null)
        {
            cacheObject = new ResourceCacheImpl();
        }

        globalCache = (ResourceCache) cacheObject;
        //初始化资源缓存器的参数，包括缓存文件个数，使用LRUMap缓存
        globalCache.initialize(rsvc);

        log.trace("Default ResourceManager initialization complete.");
    } //上面是资源加载器的初始化
```

        2.资源加载器加载文件

       

```
 String resourceKey = resourceType + resourceName;
     //缓存中取资源
        Resource resource = globalCache.get(resourceKey);

        if (resource != null)
        {
            try
            {  //防止重入
                if (resource.requiresChecking())
                {
                   //刷新资源文件，判断修改时间是否有变化
                    resource = refreshResource(resource, encoding);
                }
            }
            catch (ResourceNotFoundException rnfe)
            {
               //文件找不到重新加载，清理缓存
                globalCache.remove(resourceKey);

                return getResource(resourceName, resourceType, encoding);
            }
            catch (ParseErrorException pee)
            {//...
            }
            catch (RuntimeException re)
            {//...
            }
        }
        else
        {
            try
            {
                //去磁盘加载vm文件
                resource = loadResource(resourceName, resourceType, encoding);
             //缓存功能是否开启 
            //REOURCE_LOADER_NAME.resource.loader.cache 通过这个key
            //来设置,REOURCE_LOADER_NAME 是设置resource loader 时候的key
          //engine.setProperty(Velocity.RESOURCE_LOADER,REOURCE_LOADER_NAME 
                if (resource.getResourceLoader().isCachingOn())
                {
                    globalCache.put(resourceKey, resource);
                }
            }
            catch (ResourceNotFoundException rnfe)
            { //...            }
        }

        return resource;
```

   //先保存一下

 

```
/** 整理一下初始化资源加载器的参数**/
参数可以直接velocityEngine.setProperties(key,value);
也可以extendedProperties = new ExtendedProperties();然后放入这个扩展属性中，然后把扩展属性设置到引擎属性velocityEngine.setExtendedProperties
如果两个都设置，底层会做两个properties的合并，当然也没必要两个一起弄了，让出出问题。
下面都是properties中需要添加的属性的key和value
1. resource.loader = reourceLoader (资源加载器名称，名字随便取)
2. reourceLoader.resource.loader.class =ClasspathResourceLoader.class.getName(); //junit 资源加载器
3. reourceLoader.cache=true (是否缓存资源文件)
4. reourceLoader.modificationCheckInterval=0 (检查文件修改时间，默认为0，每次都检查)
```

 

         

二、文件渲染

 首先值得注意的是SimplePool 性能值得考究，RuntimeConstants.PARSER\_POOL\_SIZE大小值得思考。RuntimeConstants.PARSER\_POOL\_CLASS 可以替换原有的池，底层inputStream转换为char\[]

 有关渲染过程找到了两篇比较好的文章：

http://jiangbo.me/blog/2011/08/19/velocity\_overview/

http://www.khotyn.com/2011/07/22/velocity\_sourcecode/

 

 上传了一篇淘宝关于velocity优化的文章