Grails多数据源支持和src/groovy下使用service
多数据源支持 我们使用的是Mysql数据库,一主多从。业务处理需要记录修改的时候,使用主库;业务查询分析的时候使用从库。主库和从库是基于复制的,保证数据的一致性。在开发的时候,可以使用多数据源,配置如下: grails自2.0以后提供了多数据源的支持,配置如下: DataSource.groovy dataSource?{ ??username?=?"" ??password?=?"" ??dbCreate?=?"none"?//?one?of?'create',?'create-drop','update' ??url?=?"" } dataSource_update?{ ??username?=?"" ??password?=?"" ??dbCreate?=?"none"?//?one?of?'create','update' ??url?=?"" } MyService.groovy class?MyService?{ ????????def?dataSource def?dataSource_update ????????def?selectMethod()?{ def?sql=new?groovy.sql.Sql(dataSource) def?result=sql.rows("select?count(*)?c?from?user?limit?1;") println?"update?data?service?result?"+result ????????} ????????def?updateMethod(){ ????????????????def?sql=new?groovy.sql.Sql(dataSource_update) ????????????????sql.execute("update?user?set?email='xyz@163.com.cn';"); ????????} } 使用多数据源还存在其他场景,这里不做分析。 使用外部配置文件 日志配置、数据源配置和一些业务的特别需求等,如果没有外部配置,每次修改都得重新打包。这样是不明智的做法。我们需要将这些配置放在外部,需要改动时能很方便的修改,也避免了重复打包问题。我通常采用的方法是如下: 1-创建文件 conf/config.properties 2-将此配置文件拷贝到 classpath 下 #config?datasource driverClassName=com.mysql.jdbc.Driver 3-在DataSource.groovy使用 import?org.springframework.core.io.support.PropertiesLoaderUtils import?org.springframework.core.io.ClassPathResource def?config?=?PropertiesLoaderUtils.loadProperties(new?ClassPathResource("config.properties")) dataSource?{ pooled?=?true driverClassName?=?config.getProperty("driverClassName") } 其他配置文件,如果想在外部修改,也可以使用此处理办法。 在src/groovy下使用service和log controller、job中可以直接使用定义的service(服务类运行时是单件模式),但在src/groovy下需要做些工作,其中一种解决办法如下: src/groovy/MyClass.groovy import?org.apache.commons.logging.LogFactory; import?org.codehaus.groovy.grails.commons.ApplicationHolder?as?AH class?MyClass{ ????private?static?final?log?=?LogFactory.getLog(this) ????def?ctx?=?AH.application.mainContext ????def?authService=ctx.authService ???? ????def?method(){ ????????log.debug?"into?MyClass?method" ????} } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |