spring session cpu占用过高
集成spring session很简单,只需几行代码即可。
@Configuration
@EnableRedisHttpSession
public class SessionConfig {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private Integer port;
@Value("${redis.database}")
private Integer database;
@Bean
public RedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setDatabase(database);
factory.setPort(port);
factory.setTimeout(10000);
return factory;
}
}
但请注意,使用EnableRedisHttpSession的默认配置,有可能造成cpu占用过高。这是因为默认使用的是SimpleAsyncTaskExecutor,导致监听redis keyEvent事件时频繁创建线程,造成性能消耗。因此解决方案是定义线程池即可。
@Bean
public ThreadPoolTaskExecutor springSessionRedisTaskExecutor() {
ThreadPoolTaskExecutor springSessionRedisTaskExecutor = new ThreadPoolTaskExecutor();
springSessionRedisTaskExecutor.setCorePoolSize(8);
springSessionRedisTaskExecutor.setMaxPoolSize(16);
springSessionRedisTaskExecutor.setKeepAliveSeconds(10);
springSessionRedisTaskExecutor.setQueueCapacity(1000);
springSessionRedisTaskExecutor.setThreadNamePrefix("SESSION_TASK_EXEC");
return springSessionRedisTaskExecutor;
}
有关spring session的实现原因可参考文章:https://www.cnkirito.moe/spring-session-4/。