存储INI文件在内存中

问题描述:

我写一个使用INI文件来存储所有的状态代码(错误,成功代码等),一个非常简单的版本是这样的应用程序:存储INI文件在内存中

[success] 
000=Status code not found. 

[error] 
000=Error code not found. 
001=Username/Password not found. 

我的CF组件与工作使用下面的代码:

component hint="Set of tools to interact with status codes."{ 
    public function init(string codefile) any{ 
     this.codefile = Arguments.codefile; 
    } 

    public function getCodeString(string type, string code) string{ 
     var code = getProfileString(Variables.codefile, Arguments.type, Arguments.code); 
     return code; 
    } 
} 

我认为当我打电话的getProfileString是Railo打开文件情况,搜索键和返回值。所以随着我的应用程序的增长,我有更多的代码,我期望这个过程会减慢。那么是否有一种方法可以在我的init方法中打开文件,并将其全部读入变量范围,然后从那里调用getProfileString?

+0

确定。我看不出为什么你不能使用数组来存储数据,然后从那里得到错误代码... – alexy13 2011-04-08 19:16:21

+0

嗯,我可以使用一个数组,但是ini文件更容易进入并编辑和查看,特别是如果有人给我发电子邮件,并说他们收到错误代码#xxx – 2011-04-08 19:27:05

如果您想坚持使用.ini方法,您甚至可以在o​​nApplicationStart中解析您的ini文件,并将数据推送到应用程序范围中,如推荐用于@Sergii的XML文件。

做这样的事情:

var sections = getProfileSections(variables.codeFile); 
var sectionEntries = []; 
var indx = 0; 
for (key in sections){ 
    sectionEntries = listToArray(sections[key]); 
    application[key] = {}; 
    for (indx=1; indx <= arraylen(sectionEntries); indx++){ 
      application[key][sectionEntries[indx]] = getProfileString(variables.cfgFile,key,sectionEntries[indx]); 
    } 
} 

没有在Railo测试这一点,但它应该在的ColdFusion 9上班至少

+0

这看起来像是我想要做的最好的解决方案。 – 2011-04-09 13:59:34

因为您使用的是Railo,所以可能有最简单的解决方案:将文件放入RAM文件系统。

文件的完整路径看起来像ram:///some/path/to/config.ini

很明显,您需要首先将文件写入RAM,可能是首次请求。

组件的非常轻微修改后的版本可能看起来是这样的:

component hint="Set of tools to interact with status codes."{ 

    public function init(string codefile, string.ramfile) any{ 
     variables.codefile = arguments.codefile; 
     variables.ramfile = arguments.ramfile; 
    } 

    public function getCodeString(string type, string code) string{ 

     if (NOT fileExists(variables.ramfile)) { 
      fileCopy(variables.codefile, variables.ramfile); 
     } 

     return getProfileString(variables.ramfile, arguments.type, arguments.code); 

    } 
} 

请注意,我在init改变this.codefilevariables.codefile

任何方式,我也不知道ini文件是最方便和可维护的解决方案。你需要每次解析它,对吧?如果您需要配置文件,请使用XML。只需在onApplicationStart中解析它并将数据推送到应用程序范围。