我有一堆小服务,方便地称为微服务(Microservices ;-),它们都具有相同的启动行为。它们被组织成包 - 每个包代表一个服务。包的命名方式如下:
但是正如你可能已经猜到的那样,这会打印出太多的内容:
com.foo.bar.Application
其中,com.foo是域名部分,bar是实际服务名称,Application是我的主类实例,包含main方法。
现在我想要做的是,在服务启动时打印出一个标准化的日志消息,显示用户可以查询服务信息的URL。按照定义,获取服务信息的URL应该如下构建:
IP:PORT/bar/admin/info
我试过使用getClass()等方法来获取bar.name,但是都不起作用。因此我尝试了以下方法:
LOG.info("Access URLs:\n----------------------------------------------------------\n" +
"\tLocal: \t\thttp://127.0.0.1:{}/" + getMyClass() + "/info\n" +
"\tExternal: \thttp://{}:{}/" + getMyClass() + "/info\n----------------------------------------------------------",
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port")
);
/**
* Get the name of the application class as a static value, so we can show it in the log
*/
public static final Class[] getClassContext() {
return new SecurityManager() {
protected Class[] getClassContext(){return super.getClassContext();}
}.getClassContext();
};
public static final Class getMyClass() { return getClassContext()[2];}
但是正如你可能已经猜到的那样,这会打印出太多的内容:
class com.foo.bar.Application
我想要的只是
bar
我该如何实现这个?
顺便说一下,我正在使用Java 8和Spring Boot——如果有帮助的话。
最好的问候,
Chris