
本文探讨了在spring应用中如何高效地定时刷新一个bean,特别是针对需要周期性更新且创建成本较高的资源(如安全令牌)的场景。由于`@scheduled`方法不能直接返回bean,文章提出了通过引入独立的令牌持有者或优化令牌服务自身来封装令牌管理逻辑,并结合`@scheduled`注解实现令牌的定时更新与复用。
在许多企业级应用中,我们经常需要与外部服务进行交互,这些服务可能要求使用短期有效的安全令牌(如OAuth2 Access Token)。为了性能考虑,我们不希望在每次请求时都重新生成令牌,而是希望在令牌过期前(例如,令牌有效期5分钟,我们每4分钟刷新一次)进行周期性刷新并复用。
Spring框架提供了强大的调度功能,通过@Scheduled注解可以方便地实现定时任务。然而,一个常见的误解是,能否将@Scheduled方法直接标记为@Bean并返回一个值,从而实现定时更新一个Bean。实际上,Spring的@Scheduled注解要求其修饰的方法返回类型为void,这意味着我们不能直接通过这种方式来刷新一个Bean。
为了解决这一问题,我们需要采用一些设计模式来间接实现Bean的定时刷新。本文将介绍两种主要的方法。
这种方法的核心思想是创建一个独立的Spring Bean,专门用于持有和提供当前有效的安全令牌。@Scheduled定时任务将负责调用令牌生成服务获取新令牌,并将其存储到这个持有者Bean中。
首先,创建一个简单的类来存储令牌。为了确保在多线程环境下令牌的可见性,推荐使用volatile关键字修饰令牌字段。
import org.springframework.stereotype.Component;
@Component
public class SecurityTokenHolder {
private volatile String token; // 使用 volatile 确保多线程可见性
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}接下来,配置一个带有@Scheduled注解的方法。这个方法将注入令牌生成服务(例如,Authorization服务)和SecurityTokenHolder,然后调用令牌生成服务获取新令牌,并更新SecurityTokenHolder中的令牌。为了确保应用启动时即有可用令牌,可以使用@PostConstruct进行初始化。
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.UUID;
// 假设 Authorization 是一个负责生成令牌的服务
@Component
class AuthorizationService {
public String generateNewToken() {
// 模拟令牌生成逻辑,例如调用外部认证服务
return "secure-token-" + UUID.randomUUID().toString().substring(0, 8) + "-" + System.currentTimeMillis();
}
}
@Configuration
@EnableScheduling // 启用 Spring 的定时任务功能
public class AuthSchedulerConfig {
private final AuthorizationService authorizationService;
private final SecurityTokenHolder tokenHolder;
public AuthSchedulerConfig(AuthorizationService authorizationService, SecurityTokenHolder tokenHolder) {
this.authorizationService = authorizationService;
this.tokenHolder = tokenHolder;
}
@PostConstruct // 应用启动时立即生成并设置初始令牌
public void initToken() {
String initialToken = authorizationService.generateNewToken();
tokenHolder.setToken(initialToken);
System.out.println("Initial security token generated: " + initialToken);
}
/**
* 定时刷新安全令牌。
* fixedDelayString: 使用 Spring 表达式语言从属性文件读取延迟时间,
* 若未配置则默认每4分钟执行一次 (PT4M 表示 Period of Time 4 Minutes)。
*/
@Scheduled(fixedDelayString = "${security.token.refresh.delay:PT4M}")
public void refreshSecurityToken() {
String newToken = authorizationService.generateNewToken();
tokenHolder.setToken(newToken);
System.out.println("Security token refreshed at " + new Date() + " with new token: " + newToken);
}
}其他需要使用令牌的组件(例如,一个执行REST调用的Manager)可以直接注入SecurityTokenHolder,并通过其getToken()方法获取当前有效的令牌。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate; // 假设使用 RestTemplate
@Component
public class Manager {
private final String apiPath;
private final SecurityTokenHolder tokenHolder;
private final RestTemplate restTemplate;
public Manager(
@Value("${my.api.path}") String apiPath,
SecurityTokenHolder tokenHolder,
RestTemplate restTemplate) {
this.apiPath = apiPath;
this.tokenHolder = tokenHolder;
this.restTemplate = restTemplate;
}
public Object performSecureApiCall() {
String token = tokenHolder.getToken(); // 从持有者获取当前令牌
if (token == null) {
throw new IllegalStateException("Security token is not available.");
}
System.out.println("Manager using token: " + token + " for API call to: " + apiPath);
// 实际的 REST 调用逻辑,例如添加令牌到请求头
// HttpHeaders headers = new HttpHeaders();
// headers.setBearerAuth(token);
// HttpEntity<?> entity = new HttpEntity<>(headers);
// return restTemplate.exchange(apiPath, HttpMethod.GET, entity, Object.class).getBody();
return "API call result with token: " + token; // 示例返回值
}
}这种方法更加符合“单一职责原则”,将令牌的生成、持有和提供职责都封装在同一个服务中。令牌生成服务(例如,AuthorizationService)不仅负责生成令牌,还负责维护其当前有效令牌的状态。
将AuthorizationService进行重构,使其内部包含一个字段来存储当前令牌,并提供一个方法供外部获取该令牌,以及一个方法供调度器调用以更新内部令牌。
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.UUID;
import java.util.Date;
@Component
public class AuthorizationService {
private volatile String currentToken; // 内部持有当前有效令牌
@PostConstruct // 应用启动时初始化令牌
public void initializeToken() {
this.currentToken = generateNewTokenInternal();
System.out.println("AuthorizationService initialized with token: " + this.currentToken);
}
/**
* 供定时任务调用的方法,用于更新内部令牌。
* 该方法返回 void,符合 @Scheduled 的要求。
*/
public void updateToken() {
this.currentToken = generateNewTokenInternal();
System.out.println("AuthorizationService internal token updated at " + new Date() + " with new token: " + this.currentToken);
}
/**
* 供其他组件获取当前有效令牌的方法。
*/
public String getToken() {
return currentToken;
}
// 内部方法,封装实际的令牌生成逻辑
private String generateNewTokenInternal() {
// 模拟令牌生成,例如调用外部服务
return "secure-token-internal-" + UUID.randomUUID().toString().substring(0, 8) + "-" + System.currentTimeMillis();
}
}定时任务的配置现在变得更简洁,它只需要注入AuthorizationService,并定时调用其updateToken()方法即可。
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
@EnableScheduling
public class AuthSchedulerConfig {
private final AuthorizationService authorizationService; // 注入重构后的服务
public AuthSchedulerConfig(AuthorizationService authorizationService) {
this.authorizationService = authorizationService;
}
/**
* 定时调用 AuthorizationService 的 updateToken 方法来刷新令牌。
*/
@Scheduled(fixedDelayString = "${security.token.refresh.delay:PT4M}")
public void refreshAuthorizationToken() {
authorizationService.updateToken(); // 直接调用服务的方法更新令牌
}
}其他组件现在直接注入AuthorizationService,并通过其getToken()方法获取令牌。这种方式使得令牌的来源和管理更加清晰。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class Manager {
private final String apiPath;
private final AuthorizationService authorizationService; // 注入 AuthorizationService
private final RestTemplate restTemplate;
public Manager(
@Value("${my.api.path}") String apiPath,
AuthorizationService authorizationService,
RestTemplate restTemplate) {
this.apiPath = apiPath;
this.authorizationService = authorizationService;
this.restTemplate = restTemplate;
}
public Object performSecureApiCall() {
String token = authorizationService.getToken(); // 直接从服务获取当前令牌
if (token == null) {
throw new IllegalStateException("Security token is not available from AuthorizationService.");
}
System.out.println("Manager using token from AuthorizationService: " + token + " for API call to: " + apiPath);
// 实际的 REST 调用逻辑
return "API call result with token from service: " + token; // 示例返回值
}
}尽管Spring的@Scheduled方法不能直接返回Bean,但通过引入一个独立的令牌持有者Bean,或者更推荐地,通过优化令牌提供服务自身来管理和提供令牌,我们可以优雅地实现Bean的定时刷新。第二种方法(优化令牌服务自身)通过将令牌的生成、存储和提供职责封装在一个服务中,提高了代码的内聚性和可维护性,是更推荐的设计模式。通过这些策略,可以有效管理应用程序中需要周期性刷新的资源,从而提高系统性能和资源利用率。
以上就是Spring 定时刷新Bean的策略:以安全令牌为例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号