Giter Club home page Giter Club logo

jsr107-magnolia's Introduction

jsr107-magnolia

Build Status Maven Central javadoc codecov snapshots

See

After installation, you can cache the result of any method of any guice managed bean by adding the @CacheResult annotation.

@CacheResult(cacheName = "CinemaUtil-sortedMovies")
public List<Map.Entry<Movie, Set<RoleType>>> sortedMovies(Person person) {
   ...
}

In this case in the magnolia cache configuration automaticly a cache 'CinemaUtil-sortedMovies' will appear.

Possible cache values

The cache values may be null and Optional. This implementation will arrange that no nulls are stored in the underlying magnolia cache. If the value is Optional, the value of the Optional will be serialized.

Non serializable values are only possible if the underlying eh-cache is configured not to store to disk.

Model classes

Sadly, "model classes are not instantiated by guice, but by Magnolia itself", so they cannot be proxied by guice.

Installation

Download the most recent jar from: https://oss.sonatype.org/content/repositories/snapshots/nl/vpro/jsr107-magnolia and install it like you’d normally would.

Or you can add this to your pom.xml

<dependency>
  <groupId>nl.vpro</groupId>
  <artifactId>jsr107-magnolia</artifactId>
  <version>1.19</version>
</dependency>

Configuration

For versions older then 1.14 caches were configured like so in the JCR-tree: cache configuration From 1.14 onwards Magnolia 5.5.4 uses ehcache3 so the configuration has changed and looks like this: cache configuration

Cache-configurations can be automaticly created using tasks on the version handler of your module. E.g. like this:

@Slf4j
public class CinemaVersionHandler extends DefaultModuleVersionHandler {

    @Override
    protected List<Task> getBasicInstallTasks(InstallContext installContext) {
        List<Task> tasks = super.getBasicInstallTasks(installContext);
        tasks.addAll(CreateConfigurationTasks.createConfigurationTasks(CinemaUtilWithCaching.class));
        log.info("Created tasks {}", tasks);
        return tasks;
    }
}

Default settings could be configured using the nl.vpro.magnolia.jsr107.DefaultCacheSettings annotation:

    @CacheResult(cacheName = "CinemaUtil-scheduleForChannel")
    @DefaultCacheSettings(blockingTimeout = 30000)
    List<ScheduleItem> scheduleForChannel(String channel, LocalDate date) {
        log.info("Getting movies for  {} {}", channel, date);
        MediaSearch search = new MediaSearch();
        ....

If you use an 'exception cache' too, you may want to configure this separately. You need to wrap a @nl.vpro.magnolia.jsr107.Defaults then.

 @CacheResult(cacheKeyGenerator = ImageCacheKey.class, cacheName = ASSET_LINKS_CACHE, exceptionCacheName = ASSET_LINKS_CACHE + "-exceptions")
    @Defaults(
        overrideOnUpdate = true,
        exceptionCacheSettings = @DefaultCacheSettings(maxElementsInMemory = 200, timeToLiveSeconds = 300),
        cacheSettings = @DefaultCacheSettings(maxElementsInMemory = 2000, timeToLiveSeconds = 3600)
    )
    @Override
   public String getAssetLink(Image image, String variation) {

Actually the code can also be accessed if you want to configure a cache programmaticly for some other reason. This more or less eliminates the need to configure cache outside code altogether. The cache settings are in this way still visible in the JCR-tree, and can be modified and viewed via JMX, but they can be maintained in the code of your application.

       // Create browser cache for api clients
        setInstallOrUpdateTask(CreateCacheConfigurationTask.builder()
            .name(CACHE)
            .settings(CacheSettings.builder()
                .eternal(true)
                .overflowToDisk(true)
                .diskSpoolBufferSizeMB(500)
                .maxElementsInMemory(200)
                .diskExpiryThreadInterval(Duration.ofHours(24))
            )
            .overrideOnUpdate(true)
            .build());

MgnlCacheManager

The nl.vpro.magnolia.jsr107.MgnlCacheManager implementation of javax.cache.CacheManager contains a few utilities which may come in useful when interacting with caches. E.g. utilities to get existing values from the caches, or to retrieve all keys, which can be used when activily refreshing entries in the cache (e.g. in conjection with @javax.cache.annotation.CachePut)

A MgnlCacheManager can simply be obtained using @Inject.

Cache Event Listening

Since version 1.16 we will also support cache listening. E.g.

    @Inject
    public MediaPlayerPageCache(
        Provider<VtkUtil> vtkUtil,
        ServerConfiguration serverConfiguration,
        Provider<MgnlCacheManager> mgnlCacheManager,
        @Named(SystemEventBus.NAME) EventBus systemEventBus
) {
        this.vtkUtil = vtkUtil;
        this.serverConfiguration = serverConfiguration;
        this.mgnlCacheManager = mgnlCacheManager;
        systemEventBus.addHandler(ModulesStartedEvent.class, this::registerCacheEntryListener);
    }

    protected void registerCacheEntryListener(ModulesStartedEvent event) {
        log.info("{}", event);
        mgnlCacheManager.get().getCache(CACHE_NAME).registerCacheEntryListener(new MutableCacheEntryListenerConfiguration<>(
            new FactoryBuilder.SingletonFactory<>(new Listener()),
            new FactoryBuilder.SingletonFactory<>(e -> true),
            false,
            true));
    }

jsr107-magnolia's People

Contributors

dependabot[bot] avatar mihxil avatar raanelom avatar ricojansen avatar vprodigitaal avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsr107-magnolia's Issues

Provide bootstrap for sample cache configuration

When using non persistent ehcache on nonserializable objects, the persistence has to be turned off:
/modules/cache/config/cacheFactory/caches/CACHE_NAME/persistence@strategy=none
It would be cool if this could be preconfigured and provided as a sample bootstrap file (instead of the cache configuration screenshot)

2016-05-09 14:00:44,119 ERROR net.sf.ehcache.store.disk.DiskStorageFactory : Disk Write of org.jsr107.ri.annotations.DefaultGeneratedCacheKey@56833e4a failed: java.io.NotSerializableException: info.magnolia.module.site.ConfiguredSite at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548) at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:441) at net.sf.ehcache.Element.writeObject(Element.java:875) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1028) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348) at net.sf.ehcache.util.MemoryEfficientByteArrayOutputStream.serialize(MemoryEfficientByteArrayOutputStream.java:97) at net.sf.ehcache.store.disk.DiskStorageFactory.serializeElement(DiskStorageFactory.java:403) at net.sf.ehcache.store.disk.DiskStorageFactory.write(DiskStorageFactory.java:385) at net.sf.ehcache.store.disk.DiskStorageFactory$DiskWriteTask.call(DiskStorageFactory.java:477) at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1071) at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1055) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)

Caches are in the wrong path as of 5.5.5

Since Magnolia 5.5.5 as per MGNLCACHE-134.

The path in CreateConfigurationTasks.java is currently set to /modules/cache/config/cacheFactory/caches where as, caches will now only be found if they're in the caches of a delegateFactory, e.g. /modules/cache/config/cacheFactory/delegateFactories/ehcache3/caches.

Working with a clean install, the /modules/cache/config/cacheFactory/caches did not exist, so initially I added that one as well. In that original folder/path, they will be created but will never be flushed by TTL etc.

Changing the paths seems to resolve the issue.
I'm currently using an extra startup task to move the sub nodes of /modules/cache/config/cacheFactory/caches to /modules/cache/config/cacheFactory/delegateFactories/ehcache3/caches and all seems well.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.