1.问题的出现
项目使用的是springboot 2.1.6.RELEASE版本,使用了jasypt-spring-boot-starter 3.0.3来进行对配置文件进行加密操作,在压测过程中使用JProfiler发现,另外注意下压测过程中的cpu\内存\还有可能是带宽不足导致压不上去
RefreshScopeRefreshedEventListener中的调用ClassUtils.forName占用不少的cpu
2.原因
jasypt-spring-boot-starter 3.0.3使用了jasypt的CachingConfiguration用于做配置文件动态刷新,代码如下:
@Configuration
public class CachingConfiguration {
@Bean
public RefreshScopeRefreshedEventListener refreshScopeRefreshedEventListener(ConfigurableEnvironment environment, EncryptablePropertySourceConverter converter) {
return new RefreshScopeRefreshedEventListener(environment, converter);
}
}
实现了spring的事件监听接口,spring 接收前端请求当请求处理后,Spring MVC 会发送 RequestHandledEvent 事件,由于此监听器中的isAssignable调用ClassUtils.forName
使用类加载器进行加载类REFRESHED_EVENT_CLASS 与 ENVIRONMENT_EVENT_CLASS 来判断当前收到的事件是否是刷新事件,此处引起了cpu的消耗
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class RefreshScopeRefreshedEventListener implements ApplicationListener<ApplicationEvent> {
public static final String REFRESHED_EVENT_CLASS = "org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent";
public static final String ENVIRONMENT_EVENT_CLASS = "org.springframework.cloud.context.environment.EnvironmentChangeEvent";
private final ConfigurableEnvironment environment;
private final EncryptablePropertySourceConverter converter;
public RefreshScopeRefreshedEventListener(ConfigurableEnvironment environment, EncryptablePropertySourceConverter converter) {
this.environment = environment;
this.converter = converter;
}
@Override
@SneakyThrows
public void onApplicationEvent(ApplicationEvent event) {
if (isAssignable(ENVIRONMENT_EVENT_CLASS, event) || isAssignable(REFRESHED_EVENT_CLASS, event)) {
log.info("Refreshing cached encryptable property sources");
refreshCachedProperties();
decorateNewSources();
}
}
boolean isAssignable(String className, Object value) {
try {
return ClassUtils.isAssignableValue(ClassUtils.forName(className, null), value);
} catch (ClassNotFoundException e) {
return false;
}
}
3.问题处理
使用了非boot-starter方式引入jar
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>3.0.3</version>
</dependency>
不开启注解@EncryptablePropertySources,使用自定义Configuration来导入加密功能,不过损失了动态刷新配置,因项目不使用动态刷新加密的配置
@Configuration
@Import({EncryptablePropertyResolverConfiguration.class})
public class EncryptableConfiguration {
private static final Logger log = LoggerFactory.getLogger(EncryptableConfiguration .class);
public EncryptableConfiguration () {
}
@Bean
public static EnableEncryptablePropertiesBeanFactoryPostProcessor enableEncryptablePropertySourcesPostProcessor(ConfigurableEnvironment environment, EncryptablePropertySourceConverter converter) {
return new EnableEncryptablePropertiesBeanFactoryPostProcessor(environment, converter);
}
}
配置文件的yml中可使用如下来针对jwt key进行密文配置
jwt.private.key=ENC(ABCDE)
jasypt.encryptor.password=123
jasypt.encryptor.algorithm=PBEWithMD5AndDES
项目中可以使用类来进行需要加密处理的业务
@Resource
private StringEncryptor stringEncryptor;