Grails: changing dataSource url at runtime to achi

2019-02-28 16:24发布

I'm building a multi tenant application with Grails and I want to keep separate databases. I need to change the url dynamically at runtime to point GORM to different database.

I have a front-end acting as a balancer distributing requests to a cluster of backend hosts. Each backend host runs a Grails 2.3.5 instance and a mysql-server with several databases (one per tenant). I would like to change dataSource dynamically so that GORM can access domain entities on the right database.

Any ideas ?

Thanks

1条回答
爷的心禁止访问
2楼-- · 2019-02-28 16:31

You can configure multiple data source in your DataSource.groovy, have a look in the blog.

In your domains: add which data source your domain can interact, eg.,

static mapping = {
    datasources(['dataSource1', 'dataSource2'])
}

or "ALL" for all datasources, eg.,

static mapping = {
    datasource 'ALL'
}

and then you can make queries with data source name to which you want to get/set data, eg.,

def userClass = User.class
User user = userClass.dataSource1.findByName('username')

Ref:- multipleDatasources, Querying on multiple datasource in grails

查看更多
登录 后发表回答