onApplicationStart在ColdFusion中是个好主意吗?

CFU*_*ser 2 coldfusion scope restart

我必须在ColdFusion中使用变量(查询结果集),它将从其他应用程序数据库获取结果,并存储在Coldfusion Application中.

主要思想是我只需要在服务器启动时调用其他Application DB并将结果缓存在本地.我需要在我的应用程序的其他页面中读取变量.我不会在任何页面中覆盖该变量.

在谷歌上搜索我发现' onApplicationStart'在应用程序启动时分配变量很有用.

使用onApplicationStart罚款或有其他方式吗?我们可以在启动时(一次)分配一个变量.

如果onApplicationStart 没关系:怎么用?也许任何明确解释的链接都是有帮助的.

Dan*_*sen 8

这得看情况.此查询数据多久更新一次?如果它真的没有变化,那么onApplicationStart()是一个很好的放置它的地方.但是,如果它会经常改变每,你可以告诉ColdFusion的到缓存查询一定的时间周期,那么你就需要与onApplicationStart()烂摊子,而是当你调用查询将返回自动缓存结果(在指定的时间段内).

无论如何,我会编写一个自定义函数来检索数据.然后从onApplicationStart()或其他地方调用它将是微不足道的.

Startup.cfc :(任意你喜欢的名字)

<!--- Replace the datasource name with your db name --->
<cffunction name="getStartupQuery" hint="Returns a query recordset for startup">
    <cfargument name="datasource" required="no" type="string" default="OtherAppDB">
    <!--- Init the query variable --->
    <cfset var result = queryNew("id")>

    <!-- Get the query dataset --->
    <cfquery name="result" datasource="#arguments.datasource#">
         YOUR QUERY HERE
    </cfquery>

    <cfreturn result>
</cffunction>
Run Code Online (Sandbox Code Playgroud)

Application.cfc :(只是重要的部分)

<cffunction name="onApplicationStart">
    <!--- init the startup.cfc, then retrieve the data
    and save it to the application scope. Remember the component name must match
    your component above --->
    <cfset var startup = createObject("component", "startup")>
    <cfset application.varFromOtherDB = startup.getStartupQuery()>
    <cfreturn true>
</cffunction>
Run Code Online (Sandbox Code Playgroud)

现在,您应该能够使用以下命令从应用程序中的任何CFM或CFC访问此变量:

<cfset myNewVar = application.varFromOtherDB>
or
#application.varFromOtherDB#
Run Code Online (Sandbox Code Playgroud)

如果您使用onApplicationStart()方法,我强烈建议您实现一种方法来重新启动应用程序.例如,请参阅此其他讨论.