Spring Cloud: Refresh scope bean

ویژگی های میکروسرویس ممکن است در طول اجرا تغییر کند. مکانیزمی برای بهروزرسانی در Spring Cloud موجود است.
از کتابخانه زیر استفاده می شود
- جاوا 17
- Spring Framework 6.1.6
- Spring Cloud Common 4.1.2
در زیر تعریف از @RefreshScope
package org.springframework.cloud.context.config.annotation;
// ...
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Scope("refresh")
@Documented
public @interface RefreshScope {
// ...
}
@RefreshScope (یا @scope (“رفرش”)) برای تنظیم یک لوبیا با دامنه تازه سازی استفاده می شود. مثال زیر یک کلاس کامپوننت است که با آن حاشیه نویسی شده است @RefreshScope، برای دسترسی به URL یک API.
@Component
@RefreshScope
public class ConfigComponent {
private String apiUrl;
public String getApiUrl() {
return apiUrl;
}
@Value("${api-url}")
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
}
دو تعریف لوبیا ایجاد می شود.
- نام “configComponent”، یک دانه تک تنه است که به اجزای دیگر تزریق می شود. این یک نمونه پروکسی است.
- نام “scopedTarget.configComponent”، یک Bean refresh scope که نمونه واقعی است. هنگامی که اقدام بهروزرسانی فعال میشود، نمونه جدید جایگزین میشود.
هنگامی که متد getApiUrl() نمونه پروکسی “configComponent” فراخوانی می شود، org.springframework.aop.framework.CglibAopProxy.DynamicAdvisedInterceptor#intercept فراخوانی خواهد شد و برای جستجوی bean “scopedTarget.configComponent” در BeanFactory.
سپس org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean فراخوانی خواهد شد. Bean “scopedTarget.configComponent” محدوده تازه سازی است، بنابراین نمونه جدید در حافظه پنهان ذخیره می شود org.springframework.cloud.context.scope.refresh.RefreshScope.
نقطه پایانی Spring Boot Actuator (/actuator/refresh) برای اقدام بهروزرسانی ماشه در دسترس است. برای آن را فعال می کند، موارد زیر را به پیکربندی اضافه کنید.
management.endpoints.web.exposure.include=refresh
عملیات در تعریف شده است org.springframework.cloud.context.refresh.ContextRefresher#refresh
public synchronized Set<String> refresh() {
Set<String> keys = refreshEnvironment();
this.scope.refreshAll();
return keys;
}
هنگامی که راه اندازی می شود، ابتدا پیکربندی از منبع پیکربندی ارائه شده توسط Spring Cloud Config، Spring Cloud Kubernetes دوباره بارگیری می شود. سپس، دانههای دامنه تازهسازی موجود حذف میشوند و دیگر نمیتوان به آنها دسترسی داشت. با استفاده از مقادیر پیکربندی جدید، یک bean جدید در نقطه نقطه ایجاد می شود.
- https://docs.spring.io/spring-cloud-commons/reference/spring-cloud-commons/application-context-services.html#refresh-scope