面试题答案
一键面试- 定义端点:
- 创建一个类,实现
Endpoint
接口(在Spring Boot 2.x中,可实现Endpoint<MyResponse>
,MyResponse
是自定义的返回数据类型)。例如:
import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.stereotype.Component; @Endpoint(id = "custom - endpoint") @Component public class CustomEndpoint { @ReadOperation public String getCustomData() { // 这里编写获取特定业务数据的逻辑,返回业务数据 return "specific business data"; } }
@Endpoint
注解用于标记该类为一个端点,id
属性指定端点的唯一标识。@ReadOperation
注解标记的方法用于处理读取请求(如果是处理写入等其他操作,还有相应的@WriteOperation
等注解)。
- 创建一个类,实现
- 暴露端点:
- 在Spring Boot 2.x中,Actuator默认暴露的端点有限。要暴露自定义端点,需在
application.properties
或application.yml
中进行配置。 - 如果使用HTTP,对于
application.properties
,可添加:
management.endpoints.web.exposure.include = custom - endpoint
- 对于
application.yml
:
management: endpoints: web: exposure: include: custom - endpoint
- 这样配置后,自定义端点就可以通过HTTP被访问了。如果使用JMX等其他方式暴露端点,也有相应的配置方式,例如通过JMX暴露所有端点:
management.endpoints.jmx.exposure.include = *
- 在Spring Boot 2.x中,Actuator默认暴露的端点有限。要暴露自定义端点,需在
- 处理端点请求并返回数据:
- 在定义端点时,
@ReadOperation
等注解标记的方法内编写处理请求逻辑。 - 如上述代码中
getCustomData
方法,在该方法内调用业务服务获取数据,例如调用数据库查询、调用其他微服务等,然后将获取到的数据返回。返回的数据类型需与方法定义的返回类型一致,Spring Boot会自动将返回的数据进行序列化(如JSON序列化,前提是添加了相应的依赖且配置正确),并返回给请求方。
- 在定义端点时,