刚发布的SSpring Boot 2.0 增强了Actuator端点基础设施的特性。最重要的变更包括:
- 支持Jersey1 RESTful Web服务
- 支持基于反应式理念的WebFlux Web App
- 新的端点映射
- 简化用户自定义端点的创建
- 增强端点的安全性
Spring Boot的actuator端点允许监控Web应用,并且可以与Web应用进行交互。在此之前,这些端点只支持Spring MVC,如果创建自定义端点的话,需要大量额外的编码和配置
端点映射
内置的端点,比如/beans
、/health
等等,现在都映射到了/application
根上下文下。比如,之前Spring Boot版本中的/beans
现在需要通过/application/beans
进行访问。
创建用户自定义端点
1、新的@Enpoint
注解简化了创建用户自定义端点的过程。如下的样例创建了名为person
的端点
@Endpoint(id = "person")
@Component
public class PersonEndpoint {
private final Map<String, Person> people = new HashMap<>();
PersonEndpoint() {
this.people.put("mike", new Person("Michael Redlich"));
this.people.put("rowena", new Person("Rowena Redlich"));
this.people.put("barry", new Person("Barry Burd"));
}
@ReadOperation
public List<Person> getAll() {
return new ArrayList<>(this.people.values());
}
@ReadOperation
public Person getPerson(@Selector String person) {
return this.people.get(person);
}
@WriteOperation
public void updatePerson(@Selector String name, String person) {
this.people.put(name, new Person(person));
}
public static class Person {
private String name;
Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
}
这个端点借助@ReadOperation和@WriteOperation注解暴露了三个方法。这个端点的定义不再需要额外的代码,它可以通过/application/person和/application/person/{name}进行访问。另外,这个端点同时还会自动部署为JMXMBean,可以通过像JConsole这样的JMX客户端来访问。
2、继承 AbstractEndpoint 抽象类
具体分析可以参考我之前写的博客Spring Boot Actuator分析,自定义端点
端点的安全性
Spring Boot 2.0采用一种稍微不同的方式来确保Web端点默认的安全性。Web端点默认是禁用的,management.security.enabled
属性已经被移除掉了。单个端点可以通过application.properties
文件中的配置来启用。比如:
endpoints.info.enabled=true
endpoints.beans.enabled=true
但是,我们还可以把endpoints.default.web.enabled
属性设置为true
,从而将actuator和用户自定义的所有端点暴露出去。