Skip to content

Groovy - How to share / cache info between events

Example

groovy
import groovy.transform.Field
import com.google.common.cache.*
import java.util.concurrent.TimeUnit

// ========================================================================================================
@Field static cacheOfAuditFieldsForDefinition = CacheBuilder.newBuilder()
        .maximumSize(100)
        .expireAfterAccess(30, TimeUnit.SECONDS) // remove se não for mexida (lida ou escrita)
        .expireAfterWrite(5, TimeUnit.MINUTES) // remove x tempo depois de escrita
        .build();

if (testVariable == "xpto") cacheOfAuditFieldsForDefinition.invalidate(msg.type)
def auditFields = cacheOfAuditFieldsForDefinition.get(msg.type, { getAuditFields(msg.type) })

Explanation

The previous example is used on the $audit keyword custumization. The important notes are:

  1. cache configuration can include maximum size, invalidation after x time without any read, invalidation after y time after write
  2. you can explicitly invalidate the cache calling invalidate
  3. in places you need the value call get, passing a second argument with the method to call whenever the cache value isn't available