使用 Spring 无反射的数据 Redis API 访问 Redis 连接池

Access Redis connection pool using Spring Data Redis without Reflection API

请帮我解决这个问题。 我想监视并定期记录有关我的应用程序中 Redis 连接池使用情况的信息。我正在通过 spring-data-redis RedisTemplate 对象使用 Redis。我知道我们可以通过 Reflection API 访问池,如下所示。由于池是通过反射访问的,在 SAST 扫描期间,我们将获得“访问说明符操作”以及如下描述:

The AccessibleObject API allows the programmer to get around the access control checks provided by Java access specifiers. In particular it enables the programmer to allow a reflected object to bypass Java access controls and in turn change the value of private fields or invoke private methods, behaviors that are normally disallowed. In this case the dangerous method you are using is 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);