akka2使用Typesafe Config库,可以使用ConfigFactory.load()加载配置文件,默认加载classpath下的application.conf, application.json and application.properties文件。ActorSystem将会把这些配置和reference.conf合并(merge)起来。

 

如果要写akka应用,将配置写在classpath根目录下的application.conf文件中。

如果要写基于akka的lib包,将配置写在jar包内的根目录下的reference.conf文件中.

问题:如果一个项目依赖多个基于akka的jar包,这些jar包中都有reference.conf,并且配置有冲突,它是怎么解决的呢?

 

可以合并config.

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为准

 

Clone the config with only the given path (and its children) retained; all sibling paths are removed.

a.withOnlyPath(String path)  //只取a里的path下的配置

 

Clone the config with the given path removed.

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