範例: 快取指令物件

可快取的指令會儲存在快取中,以便利用 Servlet 和 JavaServer Pages (JSP) 檔的類似機制來重複使用。

這個指令快取範例是簡式 stock quote 指令。

以下是 stock quote 指令 Bean。 它接受 ticker 作為輸入參數,並產生價格作為其輸出參數。

public class QuoteCommand extends CacheableCommandImpl
{
    private String ticker;
    private double price;
    // called to validate that command input parameters have been set
    public boolean isReadyToCallExecute() {
      return (ticker!=null);
    }
    // called by a cache-hit to copy output properties to this object
    public void setOutputProperties(TargetableCommand fromCommand) {
        QuoteCommand f = (QuoteCommand)fromCommand;
        this.price = f.price;
    }

   // business logic method called when the stock price must be retrieved
    public void performExecute()throws Exception {...}

    //input parameters for the command
    public void setTicker(String ticker) { this.ticker=ticker;}
    public String getTicker() { return ticker;}

    //output parameters for the command
    public double getPrice()  { return price;};
}

若要使用 stock ticker 作為快取索引鍵並使用 60 秒存活時間來快取前一個指令物件,請使用下列快取原則:

<cache>
	<cache-entry>
		<class>command</class>
		<sharing-policy>not-shared</sharing-policy>
		<name>QuoteCommand</name>
		<cache-id>
			<component type="method" id="getTicker">
				<required>true</required>
			</component>
			<priority>3</priority>
			<timeout>60</timeout>
		</cache-id>
	</cache-entry>
</cache>