2016-05-19 104 views
2

我想在沒有var定義的情況下實現定期更新的值。如何在沒有var定義的情況下定義更新值scala

比方說,如果我有Web服務器,必須做其他服務器的健康檢查,以處理用戶請求。每個用戶請求操作都會引用健康檢查結果。 如果每次處理新請求時進行健康狀況檢查,則會花費巨大的費用,而是每5分鐘最多更新一次健康狀況檢查結果值。

這很簡單如果我使用var來實現這一點。

private var result = false 
    private var lastUpdated = 0L 
    private val INTERVAL = 1000L * 60 * 5 

    def helthCheckResult = { 
    System.currentTimeMillis() match { 
     case currentTime if currentTime > lastUpdated + INTERVAL => 
     result = !result // actual code should call heathcheck impl 
     lastUpdated = currentTime 
     result 
     case _ => 
     result 
    } 
    } 

或阿卡

class HeathCheckActor(implicit system: ActorSystem) extends Actor { 
    private var result = false 
    system.scheduler.schedule(0 seconds,5 minutes,self,"update") 
    def receive = { 
    case "update" if sender == self => 
     result = !result // actual code should call heathcheck impl 
    case "get" => 
     sender ! result 
    } 
} 

他們使用var持有導致狀態。我想實現的是不用var

有沒有辦法做到這一點?

任何類型的信息/提示將不勝感激。

編輯

這是有點壞榜樣問我想達到的目標。 比方說,如果result不是簡單的finate狀態,如Boolean,但Intresult可以是Int雲代表的任何值。 換句話說,Akka FSM這樣的東西不能使用。

回答

3

我在這個情況下怎麼做,用阿卡是使用(有時濫用)context.become

在你的情況

override def receive: Receive = receiveWithLastResult(false) 

def receiveWithLastResult(lastResult: Boolean): Receive = { 
    case "update" if sender == self => 
     context.become(receiveWithLastResult(!lastResult)) 
    case "get" => 
     sender ! result 
    } 

在普通功能的情況下,你可以只收到以前值,並返回新的

case class YourValues(result: Boolean, lastUpdated: Long) 
    def helthCheckResult(previous: YourValues) = { 
    System.currentTimeMillis() match { 
     case currentTime if currentTime > lastUpdated + INTERVAL => 

     YourValues(result = !previous.result, lastUpdated = currentTime) 

     case _ => 
     previous 
    } 
+0

感謝您的回答。你能否提供代碼,這是持有價值的地方?我感覺你的代碼只是將'var'移動到其他地方。 – suish

-1

首先,重要的是要知道爲什麼你想要的,如使用VAR來保存狀態是一個絕對有效特別是對於演員而言,這也是爲了國家孤立。

然後,爲了避免變量或通常的「持有狀態」,重要的是要理解爲什麼狀態完全保留。

誰對此感興趣?誰在查詢,何時以及爲什麼?誰對狀態變化做出反應?

那麼也許只是用一個觀察者概念來替換var中的「狀態」是有效的,在這個概念中,感興趣的部分被「通知狀態改變」。

相關問題