- Mastering Spring Cloud
- Piotr Minkowski
- 472字
- 2021-08-27 18:57:04
Deregistration on shutdown
Checking how a deregistration works with a Eureka Client is a bit more of a difficult task. Our application should be shut down gracefully in order to be able to intercept a stopped event and send an event to the server. The best way for a graceful shutdown is by using the Spring Actuator /shutdown endpoint. The actuator is a part of Spring Boot and it can be included in the project by declaring the spring-boot-starter-actuator dependency in pom.xml. It is disabled by default, so we have to enable it in the configuration properties. For the sake of simplicity, it is worth disabling user/password security for that endpoint:
endpoints:
shutdown:
enabled: true
sensitive: false
To shut down the application, we have to call the POST /shutdown API method. If you receive the response {"message": "Shutting down, bye..."}, it means everything went well and the procedure has been started. Before the application is disabled, some logs starting from the line Shutting down DiscoveryClient ... will be printed out. After that, the service will be unregistered from the discovery server and it completely disappears from the list of registered services. I decided to shut down client instance #2 by calling http://localhost:8082/shutdown (you may call it using any REST client, for example, Postman), so only the instance running on port 8081 is still visible in the dashboard:
The Eureka Server dashboard also provides a convenient way to check out the history of newly created and canceled leases:
Graceful shutdown is obviously the most suitable way of stopping an application, but in the real world, we are not always able to achieve it. Many unexpected things can happen, such as a server machine restart, application failure, or just network problems at the interface between client and server. Such a situation is the same from a discovery server point of view as stopping the client application from your IDE or killing the process from the command line. If you try to do that, you will see that the discovery client shutdown procedure won't be triggered and the service is still visible in the Eureka dashboard with the UP status. Moreover, the lease will never expire.
In order to avoid this situation, the default configuration on the server side should be changed. Why does such a problem appear in the default settings? Eureka provides a special mechanism by which the registry stops expiring entries when it detects that an certain number of services didn't renew their lease in time. This should protect the registry from clearing all entries when a part of a network failure occurs. That mechanism is called self-preservation mode and can be disabled using the enableSelfPreservation property in application.yml. Of course, it should not be disabled in production:
eureka:
server:
enableSelfPreservation: false