class Message {
String code
Locale locale
String text
}
class DatabaseMessageSource extends AbstractMessageSource {
protected MessageFormat resolveCode(String code, Locale locale) {
Message msg = Message.findByCodeAndLocale(code, locale)
def format
if(msg) {
format = new MessageFormat(msg.text, msg.locale)
}
else {
format = new MessageFormat(code, locale )
}
return format;
}
}
beans = {
messageSource(DatabaseMessageSource)
}
@Immutable
class MessageKey implements Serializable {
String code
Locale locale
}
beans = {
messageCache(EhCacheFactoryBean) {
timeToLive = 500
// other cache properties
}
messageSource(DatabaseMessageSource) {
messageCache = messageCache
}
}
class DatabaseMessageSource extends AbstractMessageSource {
Ehcache messageCache
@Override
protected MessageFormat resolveCode(String code, Locale locale) {
def key = new MessageKey(code,locale)
def format = messageCache.get(key)?.value
if(!format) {
Message msg = Message.findByCodeAndLocale(code, locale)
if(msg) {
format = new MessageFormat(msg.text, msg.locale)
}
else {
format = new MessageFormat(code, locale)
}
messageCache.put new Element(key, format)
return format
}
return format;
}
}
5 comments:
Thanks for posting the info on this. Might be good to get it into the documentation.
On another note, wouldn't this be a good use case for a Hibernate query cache? The message table is unlikely to change much and there aren't any joins. It would save having to manage your own cache.
You're right, this would be better done using the query cache. So basically this is the Message class:
static mapping = {
cache true
}
And you're done.
Hi Graeme,
I've used it using Peter's suggestion and works very nicely.
Thank you both for this info!
Best regards
I used to try very hard to do it
because google return nothing.
By the way! Thanks for the caching
example because my implementation
uses Map(not efficient memory usage).
Its a timely post since am doing some caching anyway, and the approach shown is useful for other applications :) Cheers!
Post a Comment