我想使用来自网络服务的数据并将其放入骆驼 eh-cache 中。后来我想通过CacheManager在骆驼上下文之外使用这个缓存。我没有找到任何方法来做到这一点。
在下面的代码中,我跳过了 Web 服务的使用,并使用了 Map 中的数据并将其提供给 eh-cache,但我无法使用CacheManager访问此缓存。
CamelRouter 类
package com.camel;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.ehcache.EhcacheConstants;
import org.apache.camel.main.Main;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.Configuration;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.xml.XmlConfiguration;
public class Test {
private static Main main;
public static void main(String[] args) throws Exception {
main = new Main();
main.addRouteBuilder(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("timer:foo?period=5s&repeatCount=1")
.process(exchange ->{
Map<String, String> inputMap = new HashMap<>();
inputMap.put("name", "murli");
inputMap.put("lastname", "hiware");
inputMap.put("city", "pune");
exchange.getIn().setBody(inputMap);
exchange.getIn().setHeader("CamelEhcacheAction", EhcacheConstants.ACTION_PUT_ALL);
})
.to("ehcache://testCache?configUri=ehcache.xml&keyType=java.lang.String&valueType=java.lang.String")
.process(exchange -> {
URL myUrl = getClass().getResource("/ehcache.xml");
Configuration xmlConfig = new XmlConfiguration(myUrl);
CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
myCacheManager.init();
//here I want to access already created testCache component but it is creating new one.
Cache<String, String> cache = myCacheManager.getCache("testCache", String.class, String.class);
System.out.println("Cache Element:"+cache.get("name"));
System.out.println("Exchange Message:"+exchange.getIn().getBody());
});
}
});
main.run();
}
}
ehcache 配置文件
<config
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://www.ehcache.org/v3'
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd">
<cache alias="testCache">
<key-type>java.lang.String</key-type>
<value-type>java.lang.String</value-type>
<resources>
<heap unit="entries">2000</heap>
<offheap unit="MB">100</offheap>
</resources>
</cache>
<cache-template name="myDefaults">
<key-type>java.lang.Long</key-type>
<value-type>java.lang.String</value-type>
<heap unit="entries">200</heap>
</cache-template>
<cache alias="bar" uses-template="myDefaults">
<key-type>java.lang.Number</key-type>
</cache>
<cache alias="simpleCache" uses-template="myDefaults" />
</config>
请让我知道我试图实现的用例是否可以使用camel eh-cache?