天天看点

@RestControllerEndpoint 添加endpoints接口

@RestControllerEndpoint是Spring boot 2.x新增加的注解,但本质上是和@Endpoint,@WebEndpoint作用是一样的,都是为服务增加actuator 接口,方便管理运行中的服务。但是有一个明显的不同是,@RestControllerEndpoint只支持Http方式的访问,不支持JMX的访问。而且,端点的方法上面只支持@GetMapping,@PostMapping,@DeleteMapping,@RequestMapping等,而不支持@ReadOperation,@WriteOperation,@DeleteOperation。而且它返回的格式是:application/json。

下面以例子说明一下它的使用方法。

本示例代码版本:

@RestControllerEndpoint 添加endpoints接口

首先,创建一个controller,如下所示:

@Component
@RestControllerEndpoint(id = "user")
public class UserEndpointController {
	@GetMapping("getUser")
	public String getUser() {
		return "I am admin";
	}
}
           

这里需要注意的一点是,必须添加@Compoent或自定义初始化bean的config,因为@RestControllerEndpoint并不包括bean的初始化。

然后,添加配置,它这个endpoint生效:

server:
  port: 9002
management:
  endpoints:
    web:
      exposure:
        include:
        - user
           

在默认情况下,所有的endpoints是关闭的状态,这里指定开启user的endpoint,这个user就是之前添加的@RestControllerEndpoint的id。

然后输入:http://localhost:9002/actuator/user/getUser即可以访问。

这里注意一个,endpoint的接口默认的基路径是actuator,所以访问路径前必须添加这个路径 ,也可以通过配置修改这个基路径:

management:
  endpoints:
    web:
      exposure:
        include:
        - user
      base-path: /admin
           

注意,base-path必须以/开头。

然后可以输入:http://localhost:9002/admin/user/getUser

访问。

@RestControllerEndpoint 添加endpoints接口

继续阅读