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() } }