我知道在無狀態會話bean中使用實例變量是一個流行的討論主題,並且已經閱讀了其中的一些內容,但是我特別需要的是這個主題我的應用程序的實際設計。在無狀態的EJB定時器中正確使用實例變量
我的企業應用程序由幾個無狀態bean組成,它們觸發特定的事件。在這樣的事件中,我希望一些定時器也可以觸發並跟蹤某些事情(例如插入數據庫中的特定於原始事件的新數據)。
@Stateless
public class SpecificFeedbackImpl implements SpecificFeedback {
@Resource
protected TimerService timerService;
//more injections here
public String name;
public String ip;
@Timeout
public void timeoutHandler(Timer timer) {
if (timer.getInfo().toString().startsWith(name)) {
//search db for data of event with identifier "name"
//if anything found, then send to "ip"
}
}
public void stopTimer() {
for (Object o : this.timerService.getTimers())
if (((Timer) o).getInfo().toString().startsWith(name)){
((Timer)o).cancel();
}
}
@Override
public void startTimer(long interval, String eventID, String serverIP){
this.name = eventID;
this.ip = serverIP;
stopTimer();
TimerConfig config = new TimerConfig();
config.setInfo(name);
config.setPersistent(false);
timerService.createIntervalTimer(interval, interval, config);
}
}
然而,當我做了一個小測試手動調用多個計時器,以不同的間隔,eventIDs和serverIPs,我沒有從所有的定時器預期的行爲(其中一些從未超時等。 )。
上述來源是否適合所需用途,或者我應該如何設計/實施它?如果是的話,你能否提出一些建議?
存儲數據的另一種方式是將'name'屬性設置爲'static',或者如果名稱是爲每個定時器指定的,則要使用'static Map'並使用'timer.getInfo() .toString()'作爲'Map'鍵。 –