Home > AI > Backend > SpringBoot > SpringBootActuator >

Building a RESTful Web Service with Spring Boot Actuator

Step 1: add dependency

<dependency>
	<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Step 2: Config the port, the default port for actuator is 8080

# for application
server.port = 9000 

# for actuator
management.server.port= 9001 
management.server.address= localhost

Step 3: Add some codes

Example class

@Data
@AllArgsConstructor
public class Greeting {

    private final long id;
    private final String content;

}

GreetingController.java

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting sayHello(@RequestParam(name="name", required=false, defaultValue="Stranger") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

Step 3: Test

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {"management.port=0"})
public class Demo12ApplicationTests {

    @LocalServerPort
    private int port;

    @Value("${local.management.port}")
    private int mgt;

    @Autowired
    private TestRestTemplate testRestTemplate;

    @Test
    public void shouldReturn200WhenSendingRequestToController() throws Exception {
        @SuppressWarnings("rawtypes")
        ResponseEntity<Map> entity = this.testRestTemplate.getForEntity(
                "http://localhost:" + this.port + "/greeting", Map.class);

        then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    }



    @Test
    public void shouldReturn200WhenSendingRequestToManagementEndpoint() throws Exception {
        @SuppressWarnings("rawtypes")
        ResponseEntity<Map> entity = this.testRestTemplate.getForEntity(
                "http://localhost:" + this.mgt + "/actuator", Map.class);
        then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    }

}

URI:

http://localhost:9001/actuator
http://localhost:9001/actuator/health

Reference:

https://spring.io/guides/gs/actuator-service/

Related posts:
    No posts found.

Leave a Reply