akka启动时,默认加载application.conf配置文件,所以有关辅助的配置可以在该文件中定义。
此外,akka也提供可以在代码中以硬编码的方式,加入或覆盖配置。如:
// Override the configuration of the port
Config config = ConfigFactory.parseString(
"akka.remote.netty.tcp.port=" + port)
.withFallback(ConfigFactory.parseString("akka.actor.provider = akka.cluster.ClusterActorRefProvider"))
.withFallback(ConfigFactory.parseString("akka.cluster.seed-nodes = [\"akka.tcp://ClusterSystem@10.42.197.163:2551\"]"))
.withFallback(
ConfigFactory.load());
// Create an Akka system
ActorSystem system = ActorSystem.create("ClusterSystem", config);
如在application.conf中定义:
TestApp {
connection {
db {
mysql {
url = "jdbc:mysql://localhost:3306/"
dbname = "sampleDB"
driver = "com.mysql.jdbc.Driver"
username = "root"
userpassword = "password"
}
}
}
}
ActorSystem _system = ActorSystem.create("Extension-Test");
Config config = _system.settings().config();
则得到的配置如上所示,获取配置,通过:
ActorSystem _system = ActorSystem.create("Extension-Test");
Config config = _system.settings().config();
String url = config.getConfig("TestApp").getString("connection.db.mysql.url");
String url2 = config.getString("TestApp.connection.db.mysql.url");
如果使用指定TestApp加载配置如:
ActorSystem _system = ActorSystem.create("Extension-Test",
ConfigFactory.load().getConfig("TestApp"));
Config config = _system.settings().config();
通过调用发现,其自动将TestApp过滤掉了,其只作为加入配置的key值,除此以外无其它作用。
实际开发中,少用硬编码,所以第一种采用第一种方式,于配置文件中可以直接去掉TestApp,直接以connection开头