简体   繁体   中英

using ehcache in a dropwizard project

I am using dropwizard to create a RESTful service. To avoid hammering the database, I am looking for a good caching solution in java. Searching the web lead me to ehcache. I have read the documentation a bit, but currently it is not clear to me how to use ehcache in a dropwizard project.

For instance, where does the configuration file go? I just need something to help me start using the cache.

If this is difficult to integrate, what would be the most suited caching solution for dropwizard project?

Thanks!

If you ultimately want a simpler (than ehcache) cache framework/API, consider using CacheBuidler from guava:

https://code.google.com/p/guava-libraries/wiki/CachesExplained

A typical cache implementation and use requires just a few lines of code and no configuration files.

I know this is an old question, but I have been able to set it up. Here's how.

  1. Get the hibernate version. You can get this from the dependencies of dropwizard-hibernate package. eg. dropwizard-hibernate:1.3.12 depends on hibernate-core:5.2.18.Final .
  2. Add ehcache matching the exact version of hibernate, so in this case compile group: 'org.hibernate', name: 'hibernate-ehcache', version: '5.2.18.Final'
  3. Enable 2nd level caching on hibernate. Dropwizard manages configuration in config.yml. So this would be something like:
# For documentation on available options please refer io.dropwizard.db.DataSourceFactory
database:
  # any properties specific to your JDBC driver:
  properties:
    # Enable second level cache with EhCache
    hibernate.cache.use_second_level_cache: true
    hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
  1. Now, your cache should be enabled. You can now use annotations on entities to make them cacheable. see doc on @org.hibernate.annotations.Cache

I found this article to be a good start. https://www.baeldung.com/hibernate-second-level-cache . There are also other types of caches like query cache etc which may help depending on your use case.

Let me know if this helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM