akka2使用Typesafe Config庫,能夠使用ConfigFactory.load()加載配置文件,默認加載classpath下的application.conf, application.json and application.properties文件。ActorSystem將會把這些配置和reference.conf合併(merge)起來。java
若是要寫akka應用,將配置寫在classpath根目錄下的application.conf文件中。json
若是要寫基於akka的lib包,將配置寫在jar包內的根目錄下的reference.conf文件中.api
問題:若是一個項目依賴多個基於akka的jar包,這些jar包中都有reference.conf,而且配置有衝突,它是怎麼解決的呢?app
能夠合併config.ide
Returns a new value computed by merging this value with another, with keys in this value "winning" over the other one. Only ConfigObject and Config instances do anything in this method (they need to merge the fallback keys into themselves). All other values just return the original value, since they automatically override any fallback.
The semantics of merging are described in the spec for HOCON.
Note that objects do not merge "across" non-objects; if you write object.withFallback(nonObject).withFallback(otherObject), then otherObject will simply be ignored. This is an intentional part of how merging works. Both non-objects, and any object which has fallen back to a non-object, block subsequent fallbacks.測試
a.withFallback(b) //a和b合併,若是有相同的key,以a爲準this
Clone the config with only the given path (and its children) retained; all sibling paths are removed.url
a.withOnlyPath(String path) //只取a裏的path下的配置spa
Clone the config with the given path removed..net
a.withoutPath(String path) //只取a裏出path外的配置
ConfigFactory還有其餘的API,用其餘的方式(字符串、文件、Map、Properties、url等)加載配置文件,能夠查看相應的api。
配置內容便可以是層級關係,也能夠用」.」號分隔寫成一行:
akka {
host = "0.0.0.0"
port = 9999
}
akka.host = "0.0.0.0"
akka.port = 9999
配置文件還能夠在java啓動參數中加載:
-Dconfig.resource=/dev.conf
也能夠用include關鍵字引入其餘的配置。好比能夠把一些通用配置寫在一個common.conf文件中,在本身的配置中只寫個性配置,而後include 「common」:
calculator {
include "common"
akka {
remote.netty.port = 2552
}
}
測試用例:
import com.typesafe.config.ConfigFactory
import com.typesafe.config.Config
class ConfigTest extends GroovyTestCase {
def testFallback() {
String configure = """
a {
include "c.akka"
akka.loglevel = WARNING
akka.port = 0
my.own.setting = 43
}
b {
akka.loglevel = ERROR
app2.setting = "appname"
}
c {
p = 10000
akka {
host = "0.0.0.0"
port = \${p}
}
}
akka.loglevel = INFO
my.own.setting = 42
my.other.setting = "hello"
"""
Config rootConfig = ConfigFactory.parseString(configure)
println "root----" + rootConfig.root().render()
Config a = ConfigFactory.parseString(configure).getConfig("a")
println "a----" + a.root().render()
Config b = ConfigFactory.parseString(configure).getConfig("b")
println "b----" + b.root().render()
Config c = ConfigFactory.parseString(configure).getConfig("c")
println "c----" + b.root().render()
println "a_Fallback_root----" + a.withFallback(rootConfig).root().render()
println "a_Fallback_b----" + a.withFallback(b).root().render()
println "a_OnlyPath----" + a.withOnlyPath("akka").root().render()
println "c_OnlyPath----" + c.withoutPath("akka").root().render()
println c.getString("akka.host") println c.root().render() } }