Atomic Update in MS Velocity

Does Velocity support server-side atomic updates ? I'm trying to see if i can port some code (based on memcached) which implemented a ring buffer based on memcache's INCR operation.

13.10.2009 21:03:48
1 ОТВЕТ
РЕШЕНИЕ

I can't say that I'm familiar enough with memcached to know exactly what you mean, but I'm assuming that it involves locking a cached item so that one client can update it, which is supported by Velocity through the GetAndLock and PutAndUnlock methods.

Edit: OK, now I understand what you mean, no I haven't seen anything like that in Velocity. But you could write it as an extension method e.g.

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

Your usage would then become:

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
3
14.10.2009 17:15:44
In memcached you can do atomic increments and decrements in a single server roundtrip. For example, i can do a client.Increment("totalViews-" + contentId), which does the lock/increment/unlock on the server in one go.
JBland 14.10.2009 15:16:24
Thanks for that, Phil. It definitely works, though not as efficient as id like.
JBland 14.10.2009 18:36:49
This solution wouldn't work because the second call to the lock will fail.
Eugeniu Torica 7.06.2011 08:17:21
By failure I mean that request won't be blocked which will create miss update problem. Link here msdn.microsoft.com/en-us/library/dd631073.aspx
Eugeniu Torica 7.06.2011 08:22:38