【问题标题】:EHCACHE 3.x spring boot no of value in cacheEHCACHE 3.x spring boot 缓存中没有值
【发布时间】:2019-12-14 23:46:47
【问题描述】:

我正在尝试使用 ehcache。

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
      public JCacheCacheManager jCacheCacheManager() throws IOException {
        return new JCacheCacheManager(cacheManager());
      }

      @Bean(destroyMethod = "close")
      public javax.cache.CacheManager cacheManager() throws IOException {
        XmlConfiguration xmlConfig = new XmlConfiguration(new ClassPathResource("ehcache.xml").getURL());
        EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider();
        return provider.getCacheManager(provider.getDefaultURI(), xmlConfig);

      }
    }
@Service
public class AvengersService {


    @Cacheable(cacheNames="avengers" , key="#id")
    public List<String> getAvengers(String id) {
        System.out.println("Loading avengers");
        return Arrays.asList(id.toString(),"Captain America", "Hulk", "Iron Man", "Thor");
    }

}

@SpringBootApplication
@ComponentScan
public class DemoApplication   {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private AvengersService avengersService;

    public static void main(String[] args) {


          //list all the caching provider
        Iterator<CachingProvider> iterator = Caching.getCachingProviders(Caching.getDefaultClassLoader()).iterator();
        while(iterator.hasNext()) {
            CachingProvider provider = iterator.next();
            System.out.println(provider);
            if ((provider instanceof HazelcastCachingProvider)) {
                iterator.remove();
            }
        }

        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {

            JCacheCache cache = (JCacheCache) cacheManager
                    .getCache("avengers");

        for(Long i=1L;i<50001;i++) {
            List<String> t=avengersService.getAvengers(String.valueOf(i)+"a");
        cache.put(String.valueOf(i)+"a", avengersService.getAvengers(String.valueOf(i)+"a"));
        }
        System.out.println();

        Cache<Object, Object>    e= ( cache.getNativeCache());
        Iterator<Cache.Entry<Object, Object>> iterator = ( e).iterator();
        int count=1;
        while (iterator.hasNext()) {
            Cache.Entry<Object, Object> t = iterator.next();
            count++;
            System.out.println("key :" + t.getKey() + " value " + t.getValue());
        }


        System.out.println(count);

        final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();

        final Set<ObjectInstance> cacheBeans = beanServer.queryMBeans(ObjectName.getInstance("javax.cache:type=CacheStatistics,CacheManager=*,Cache=*"), null);

        for ( ObjectInstance cacheBean : cacheBeans ) {
            final CacheStatisticsMXBean cacheStatisticsMXBean = MBeanServerInvocationHandler.newProxyInstance(beanServer, cacheBean.getObjectName(), CacheStatisticsMXBean.class, false);

            System.out.println("Gets: " + cacheStatisticsMXBean.getCacheGets());
            System.out.println("Hits: " + cacheStatisticsMXBean.getCacheHits());
            System.out.println("Misses: " + cacheStatisticsMXBean.getCacheMisses());
            System.out.println("Removals: " + cacheStatisticsMXBean.getCacheRemovals());
            System.out.println("Evictions: " + cacheStatisticsMXBean.getCacheEvictions());
            System.out.println("Avg Get Time: " + cacheStatisticsMXBean.getAverageGetTime());
            System.out.println("Avg Put Time: " + cacheStatisticsMXBean.getAveragePutTime());
            System.out.println("Avg Remove Time: " + cacheStatisticsMXBean.getAverageRemoveTime());
        }
        };
    }

}
public class MyCacheEntryListener<K, V> implements CacheEventListener<K, V>, Serializable {

    @Override
    public void onEvent(CacheEvent<? extends K, ? extends V> event) {
        // TODO Auto-generated method stub

        if (EventType.UPDATED == event.getType()) {
            System.out.println("Received a " + event);
        }
    }

}
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.ehcache.org/v3"
    xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
    xsi:schemaLocation="
            http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
            http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

 <service>
      <jsr107:defaults enable-management="true" enable-statistics="true"/>
  </service>
    <cache alias="avengers">
        <key-type>java.lang.String</key-type>
        <value-type>java.util.Arrays$ArrayList</value-type>
        <expiry>
             <none/>
        </expiry>
 <listeners>
            <listener>
                <class>com.example.demo.MyCacheEntryListener</class>
                <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
                <event-ordering-mode>UNORDERED</event-ordering-mode>
                <events-to-fire-on>UPDATED</events-to-fire-on>
            </listener>
        </listeners>
        <resources>
            <heap unit="entries">2</heap>
            <offheap unit="MB">10</offheap>
        </resources>
    </cache>

</config>
spring.cache.jcache.config=classpath:ehcache.xml

块引用

在启动我的应用程序时,它会打印 2 个缓存提供程序。

HazelcastCachingProvider{delegate=HazelcastServerCachingProvider{hazelcastInstance=null}} org.ehcache.jsr107.EhcacheCachingProvider@1f57539

  1. 为什么要初始化 2 缓存提供程序?
  2. 如果是默认设置,我该如何禁用这些?
  3. 我在缓存中添加了 50000 个对象,但在迭代时我只得到“36406”对象,为什么?

【问题讨论】:

    标签: spring-boot ehcache spring-cache ehcache-3


    【解决方案1】:

    这里有很多活动部件。您不需要配置CacheManager,它是使用spring.cache.jcache.config 属性自动完成的。删除 2 个@Bean 方法。

    如果你需要访问javax.cache.CacheManager,你可以注入JCacheCacheManager,它会让你访问它封装的原生地址。

    类路径上有几个 JSR107 实现,因此 API 调用为您提供可用的东西,这是 Spring Boot 无法控制的。

    【讨论】:

    • 非常感谢@Stephane Nicoll 的即时回复。计数不正确,因为我配置的内存较少。