2009-10-13 32 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