'Use read-only DB replica for read-only GORM methods and criteria

I have a read-only MySql DB replica and want to use it for all select-based GORM requests and criteria all over the project (Grails 3.1.16) Is there any beautiful way to override the default DataSource only for the part of GORM methods (e.g. get, find)?

According to the documentation, we can use a particular dataSource for domain/service or use namespace with each method call. But I am looking for a more generic mechanism.



Solution 1:[1]

Is there any beautiful way to override the default DataSource only for the part of GORM methods (e.g. get, find)?

There is not.

You can configure as many datasources as you like but you can't declaratively express that one is used for reads and others are used for writes or anything like that. You could easily let one be the default and then be explicit when you want to do others. For example, SomeDomainClass.nameOfDatasourceUsedForReads.list() etc.

Solution 2:[2]

You can use dbresolver. For example:

db.Use(dbresolver.Register(dbresolver.Config{
    Replicas: []gorm.Dialector{mysql.Open("read_only_replica")},
}))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeff Scott Brown
Solution 2