2009-10-13 33 views
0

Velocity是否支持服務器端原子更新? 我想看看我是否可以移植一些基於memcache的INCR操作實現環形緩衝區的代碼(基於memcached)。MS Velocity中的原子更新

回答

3

我不能說我對memcached足夠熟悉知道究竟是你的意思,但我假設它涉及鎖定一個緩存項目,以便一個客戶端可以更新它,這是支持速度通過GetAndLockPutAndUnlock方法。

編輯:好的,現在我明白你的意思了,沒有我在Velocity沒見過類似的東西。但是你可以把它寫成一個擴展方法,例如然後

Imports System.Runtime.CompilerServices 

Public Module VelocityExtensions 

<Extension()> _ 
Public Sub Increment(ByVal cache As Microsoft.Data.Caching.DataCache, ByVal itemKey As String) 

    Dim cachedInteger As Integer 
    Dim cacheLockHandle As DataCacheLockHandle 

    cachedInteger = DirectCast(cache.GetAndLock(itemKey, New TimeSpan(0, 0, 5), cacheLockHandle), Integer) 

    cachedInteger += 1 

    cache.PutAndUnlock(itemKey, cachedInteger, cacheLockHandle) 

End Sub 

<Extension()> _ 
Public Sub Decrement(ByVal cache As Microsoft.Data.Caching.DataCache, ByVal itemKey As String) 

    Dim cachedInteger As Integer 
    Dim cacheLockHandle As DataCacheLockHandle 

    cachedInteger = DirectCast(cache.GetAndLock(itemKey, New TimeSpan(0, 0, 5), cacheLockHandle), Integer) 

    cachedInteger -= 1 

    cache.PutAndUnlock(itemKey, cachedInteger, cacheLockHandle) 

End Sub 

End Module 

您的使用將成爲:

Imports VelocityExtensions 
Imports Microsoft.Data.Caching 

Partial Public Class _Default 
Inherits System.Web.UI.Page 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 

    Dim myCache As DataCache 
    Dim factory As DataCacheFactory 

    myCache = factory.GetCache("MyCacheName") 

    myCache.Increment("MyInteger") 

End Sub 

End Class 
+0

Memcached中,你可以在一臺服務器往返原子做的遞增和遞減。例如,我可以做一個client.Increment(「totalViews-」+ contentId),它一次完成服務器上的鎖定/增量/解鎖。 – JBland 2009-10-14 15:16:24

+0

更新了我的答案,以展示如何做到這一點。 – PhilPursglove 2009-10-14 17:21:14

+0

謝謝你,菲爾。它絕對有效,雖然不如id這樣有效。 – JBland 2009-10-14 18:36:49