配置指令快取

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

關於這項作業

不過,在此情況下,會根據指令中呈現為輸入參數的方法和欄位來產生唯一快取 ID。 例如, GetStockQuote 指令可以使用符號作為其輸入參數。

唯一快取 ID 可以從指令名稱加上符號值產生。

若要使用指令快取,您必須執行下列動作:

程序

建立指令。
  1. 定義介面。
    「指令」介面會指定指令的最基本層面。

    您必須定義延伸指令套件中一或多個介面的介面。 指令套件由三個介面組成:

    • TargetableCommand
    • CompensableCommand
    • CacheableCommand
    實際上,大部分指令都會實作 TargetableCommand 介面,這可讓指令從遠端執行。 目標指令之指令介面的程式碼結構如下:
    ...
    import com.ibm.websphere.command.*;
    public interface MyCommand extends TargetableCommand { 
          // Declare application methods here
    }
    
  2. 提供介面的實作類別。
    撰寫延伸 CacheableCommandImpl 類別並實作指令介面的介面。 此類別包含介面中方法的程式碼、繼承自延伸介面 (例如 CacheableCommand 介面) 的方法,以及 CacheableCommandImpl 類別中的必要或抽象方法。

    您也可以置換 CacheableCommandImpl 類別中提供的其他方法的預設實作。

避免麻煩: 為了使指令快取正常運作,您必須啟用 Servlet 快取。

範例

可快取的指令會儲存在快取中,以便利用 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 秒存活時間來快取 stock quote 指令物件:

<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>