请在这里帮助我解决问题。我想在我的应用程序中监控并定期记录有关 Redis 连接池使用情况的信息。我正在通过 spring-data-redis RedisTemplate 对象使用 Redis。我知道我们可以通过反射API访问池,如下所示。由于池是通过反射访问的,因此在 SAST 扫描期间,我们将获得“访问说明符操作”以及描述如下:
AccessibleObject API允许程序员绕过Java访问说明符提供的访问控制检查。特别是,它使程序员能够允许反射对象绕过Java访问控制,进而更改私有字段的值或调用私有方法,这些行为通常是不允许的。在这种情况下,您使用的危险方法是setAccessible()
@Autowired
private RedisConnectionFactory redisConnectionFactory;
private void logData(HttpServletRequest request, Exception e) {
try {
HttpSession session = request.getSession();
JedisConnectionFactory factory = (JedisConnectionFactory)redisConnectionFactory;
if(factory != null){
Field poolField = JedisConnectionFactory.class.getDeclaredField("pool");
if(poolField != null){
poolField.setAccessible(true);
Pool<Jedis> jedisPool = (Pool<Jedis>)poolField.get(factory);
if(jedisPool!=null){
int activeNum = jedisPool.getNumActive();
int idleNum = jedisPool.getNumIdle();
int waitNum = jedisPool.getNumWaiters();
long maxBorrowWaitMs = jedisPool.getMaxBorrowWaitTimeMillis();
long meanBorrowWaitMs = jedisPool.getMeanBorrowWaitTimeMillis();
redisMonitorDetails = redisMonitorDetails+ "getNumActive="+activeNum + " NumIdle="+idleNum+ " NumWaiters="+waitNum + " MaxBorrowWaitTimeMillis="+maxBorrowWaitMs
+" MeanBorrowWaitTimeMillis="+meanBorrowWaitMs;
}
}
}
} catch (Exception exe) {
loggingService.error("Exception during logging in ExceptionHandlerController: " + exe);
}
}
使用Apache FieldUtils更新了代码,如下所示。现在,SAST扫描没有报告此问题。
Pool<Jedis> jedisPool = (Pool<Jedis>) FieldUtils.readField(JedisConnectionFactory.class, "pool", true);