[英]Spring Cache get key from the Value
I have used spring cache in a spring boot application to store value against a certain key. 我已经在spring boot应用程序中使用spring缓存来针对某个键存储值。 I now have the value, is it possible to get the key from cache against the value?
我现在有了值,是否可以根据值从缓存中获取密钥? If so Please help.
如果是这样,请帮助。
I tried using solutions regarding net.sf.ehcache.Cache
but for some reason it doesn't show any import suggestions and gives error net.sf.ehcache.Cache cannot be resolved to a type . 我尝试使用有关
net.sf.ehcache.Cache
解决方案,但是由于某种原因,它没有显示任何导入建议,并且给出错误net.sf.ehcache.Cache无法解析为类型 。 I am new to spring cache so have no clue what to do further. 我是Spring缓存的新手,所以不知道该怎么做。
The dependencies in my project are 我项目中的依赖项是
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
The code I am using is 我正在使用的代码是
public String getEmailByOtp(String otp)
{
String email = "";
Ehcache cache = (Ehcache) CacheManager.getCache("otpCache").getNativeCache();
for (Object key: cache.getKeys()) {
Element element = cache.get(key);
if (element != null) {
Object value = element.getObjectValue(); // here is the value
if(value.equals(otp)) {
email = key.toString();
}
}
}
return email;
}
Spring Cache and EhCache are two completely different implementations of caching mechanisms. Spring Cache和EhCache是两种完全不同的缓存机制实现。 Although there is a way to cast Spring-based cache to EhCache-based one, it doesn't mean Spring provides automatically its implementation.
尽管有一种方法可以将基于Spring的缓存转换为基于EhCache的缓存,但这并不意味着Spring会自动提供其实现。 You have to import the EhCache library (using Maven, Gradle, etc.).
您必须导入EhCache库(使用Maven,Gradle等)。
Here you go. 干得好。 You get an instance of
net.sf.ehcache.EhCache
which contains all the cache regions from Spring org.springframework.cache.CacheManager
. 您将获得
net.sf.ehcache.EhCache
的实例,该实例包含Spring org.springframework.cache.CacheManager
中的所有缓存区域。
EhCache cache = (EhCache) CacheManager.getCache("myCache").getNativeCache();
Then, it's not possible to access all the values directly like with the Map
. 这样,就不可能像
Map
一样直接访问所有值。 Iterate through the keys and get the particular elements matching the key. 遍历键并获取与键匹配的特定元素。 This way you iterate through all the values as well.
这样,您还可以遍历所有值。
for (Object key: cache.getKeys()) {
Element element = cache.get(key);
if (element != null) {
Object value = element.getObjectValue(); // here is the value
}
}
I haven't tested the snippets, however, I hope you get the idea. 我尚未测试代码段,但是,希望您能理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.