[转载] Reading i18n messages from the database with Grails

   如题,此文是Grails的作者的一篇文章,无奈被墙,同时也为自己做个备份。 原文URL:http://graemerocher.blogspot.com/2010/04/reading-i18n-messages-from-database.html

In a recent consulting engagement, a client wanted to know how to go about reading i18n messages from the database rather than static properties files (the default in Grails). Considering how easy this is to do I was surprised when I Googled it that there was no information on how this is achieved.


Anyway it's dead simple. Just create a domain class that models a message:

class Message {

String code

Locale locale

String text

}


Then implement a class that extends the org.springframework.context.support.AbstractMessageSource class. In the example below I am using simple GORM finders to lookup a message using the code and locale

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;

}

}


Then wire it in using Spring by configuring a "messageSource" bean in the grails-app/conf/spring/resources.groovy file:

beans = {

messageSource(DatabaseMessageSource)

}


And that's it. Now you're serving messages from the database. Of course this is a terrible inefficient implementation since we're hitting the database for ever message code used in the application. However, it's pretty easy to introduce caching. Just create a cache key:

@Immutable

class MessageKey implements Serializable {

String code

Locale locale

}


Then configure an appropriate cache bean (I'm using Ehcache) in Spring and wire it into your MessageSource:

beans = {

messageCache(EhCacheFactoryBean) {

timeToLive = 500

// other cache properties

}

messageSource(DatabaseMessageSource) {

messageCache = messageCache

}

}


Finally, update your implementation to use caching:

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;

}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值