Şu satırı dahil ederiz
import org.springframework.cloud.context.config.annotation.RefreshScope;
@RefreshScope anotasyonunu açıklaması şöyle
When this annotation is applied to a Spring component (i.e., a @Component, @Service, @RestController, etc.), the component is re-created when a configuration refresh occurs, in this case giving an updated value for ${hello.message}.You can refresh an application’s configuration by including the Spring Boot Actuator dependency, exposing the /actuator/refresh endpoint, and sending an empty POST request
Don’t use @RefreshScope in controllers
Açıklaması şöyle
Now, what about using @RefreshScope in controllers? While it's technically possible to use @RefreshScope in controllers, it's generally not recommended. Controllers are typically responsible for handling incoming requests and generating responses, and their behavior shouldn't be affected by changes to configuration settings. In addition, refreshing a controller could result in requests being dropped or delayed, which could have a negative impact on the user experience.Instead, it’s better to use @RefreshScope with beans that are responsible for handling configuration settings, such as @ConfigurationProperties or @Value beans. By using @RefreshScope with these beans, you can ensure that changes to the configuration are applied across the entire application without having to restart it.
Örnek
Şöyle yaparız. Burada Config Server'dan okunacak değer @Vaue ile çekiliyor.
@RefreshScope@RestController@RequestMapping("/secure")public static class SecureController {@Value("${hello.message}")private String helloMessage;@GetMappingpublic String secure(Principal principal) {return helloMessage;}}
Örnek
Şöyle yaparız. Burada @RefreshScope ile yeni konfigürasyonun okunabileceği belirtiliyor. Konfigürasyon verisi sürekli env.getProperty() şeklinde alınıyor.
Eğer Config Server'da bir şey değişirse Client uygulamayı ayarları tekrar okuması için tetiklemek gerekir. Şöyle yaparızimport org.springframework.core.env.Environment;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.ui.Model;@RefreshScope@RestControllerpublic class HelloController {@Autowiredprivate Environment env;@GetMapping("/hello")public ResponseEntity<String> getHello(Model model) {return new ResponseEntity<String>( env.getProperty("message"), HttpStatus.OK);}}
http://localhost:8080/actuator/refresh
Hiç yorum yok:
Yorum Gönder