使用java代码清除jboss缓存

使用java代码清除jboss缓存,java,jboss,ehcache,Java,Jboss,Ehcache,我想使用java代码清除jboss缓存,为此,我将实现以下代码: public void clearCache(String s){ String[] st=CacheManager.getInstance().getCacheNames(); Cache cache =CacheManager.getInstance().getCache(s); cache.flush(); } 这个代码正确吗?我如何确保JBoss缓存被成功清除?谢

我想使用java代码清除jboss缓存,为此,我将实现以下代码:

public void clearCache(String s){
        String[] st=CacheManager.getInstance().getCacheNames();
        Cache cache =CacheManager.getInstance().getCache(s);

        cache.flush();
    }

这个代码正确吗?我如何确保JBoss缓存被成功清除?谢谢

您的代码中有三个错误。首先,您不需要查询
getCacheNames()
;您已经在传递要清除的缓存的名称,而您只是将结果丢弃在
st
中。其次,没有像
CacheManager#getCache(String)
这样的方法;它是
getCache(String,boolean)抛出异常
,您需要传递
s,false
,并处理异常(太宽了
异常
)。最后,您从不检查缓存是否实际存在;如果有人传入一个表示不存在的缓存的名称,
cache
将为
null
,当您尝试
flush()
它时,您将得到一个NPE。

非常感谢,但是有没有办法确保缓存被清除或否?如果缓存存在,有办法吗?是的,您可以调用
cache.flush()
完全正确。如果这回答了您的问题,请投票并接受答案。