转载

Ehcache大杂烩

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

Java示例代码

package bj.ehcache;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.config.CacheConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;

/**
 * Created by BaiJiFeiLong@gmail.com at 2018/12/12 下午6:39
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableCaching
public class EhcacheApp implements ApplicationListener<ApplicationReadyEvent> {

    public static void main(String[] args) {
        SpringApplication.run(EhcacheApp.class, args);
    }

    @Component
    @Slf4j
    public static class Inner {

        @Cacheable("hello")
        public String hello(String name) {
            System.out.println(LocalDateTime.now() + " hello");
            return "Hello " + name;
        }
    }

    @Resource
    private Inner inner;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        inner.hello("apple");
        Try.run(() -> Thread.sleep(1000));
        inner.hello("apple");
        inner.hello("apple");
        Cache cache = (Cache) cacheManager.getCache("hello").getNativeCache();

        System.out.println(objectToJsonString(cache.getStatistics()));
        System.out.println("Cache keys: " + cache.getKeys());
        System.out.println("HitCount: " + cache.getStatistics().cacheHitCount());
    }

    private String objectToJsonString(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS).writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Resource
    private CacheManager cacheManager;

    @Bean
    public CacheManager cacheManager() {
        return new SimpleCacheManager() {{
            this.setCaches(Collections.singletonList(
                    new EhCacheCache(new Cache(new CacheConfiguration("hello", 100)
                            .timeToLiveSeconds(1)) {{
                        setCacheManager(new net.sf.ehcache.CacheManager());
                        initialise();
                    }})
            ));
        }};
    }
}

控制台输出

  .   ____          _            __ _ _
 /// / ___'_ __ _ _(_)_ __  __ _ / / / /
( ( )/___ | '_ | '_| | '_ // _` | / / / /
 ///  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_/__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)

2018-12-13 09:41:58.972  INFO 43705 --- [           main] bj.ehcache.EhcacheApp                    : Starting EhcacheApp on MacBook-Air-2.local with PID 43705 (/Users/yuchao/temp/java/hellomaven/target/classes started by yuchao in /Users/yuchao/temp/java/hellomaven)
2018-12-13 09:41:58.976  INFO 43705 --- [           main] bj.ehcache.EhcacheApp                    : No active profile set, falling back to default profiles: default
2018-12-13 09:42:00.516  WARN 43705 --- [           main] n.s.ehcache.config.ConfigurationFactory  : No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/Users/yuchao/.m2/repository/net/sf/ehcache/ehcache/2.10.6/ehcache-2.10.6.jar!/ehcache-failsafe.xml
2018-12-13 09:42:01.092  WARN 43705 --- [           main] reactor.netty.tcp.TcpResources           : [http] resources will use the default LoopResources: DefaultLoopResources {prefix=reactor-http, daemon=true, selectCount=4, workerCount=4}
2018-12-13 09:42:01.093  WARN 43705 --- [           main] reactor.netty.tcp.TcpResources           : [http] resources will use the default ConnectionProvider: PooledConnectionProvider {name=http, poolFactory=reactor.netty.resources.ConnectionProvider$$Lambda$287/180078856@44afefd5}
2018-12-13 09:42:01.212  INFO 43705 --- [           main] bj.ehcache.EhcacheApp                    : Started EhcacheApp in 3.067 seconds (JVM running for 4.41)
2018-12-13T09:42:01.224 hello
2018-12-13T09:42:02.239 hello
2018-12-13 09:42:02.294  INFO 43705 --- [           main] n.s.e.p.s.filter.AnnotationSizeOfFilter  : Using regular expression provided through VM argument net.sf.ehcache.pool.sizeof.ignore.pattern for IgnoreSizeOf annotation : ^.*cache/..*IgnoreSizeOf$
2018-12-13 09:42:02.304  INFO 43705 --- [           main] n.sf.ehcache.pool.sizeof.JvmInformation  : Detected JVM data model settings of: 64-Bit HotSpot JVM with Compressed OOPs
2018-12-13 09:42:02.539  INFO 43705 --- [           main] net.sf.ehcache.pool.sizeof.AgentLoader   : Extracted agent jar to temporary file /var/folders/tq/2sx8fvnn29l7hwssgj03j9s40000gn/T/ehcache-sizeof-agent9099389960610149217.jar
2018-12-13 09:42:02.539  INFO 43705 --- [           main] net.sf.ehcache.pool.sizeof.AgentLoader   : Trying to load agent @ /var/folders/tq/2sx8fvnn29l7hwssgj03j9s40000gn/T/ehcache-sizeof-agent9099389960610149217.jar
{
  "core" : { },
  "extended" : { },
  "size" : 1,
  "localHeapSizeInBytes" : 240,
  "localOffHeapSizeInBytes" : 0,
  "localDiskSizeInBytes" : 0,
  "localHeapSize" : 1,
  "localOffHeapSize" : 0,
  "remoteSize" : 0,
  "localDiskSize" : 0,
  "associatedCacheName" : "hello",
  "writerQueueLength" : 0
}
Cache keys: [apple]
HitCount: 1

文章首发: https://baijifeilong.github.io

原文  https://baijifeilong.github.io/2018/12/13/ehcache/
正文到此结束
Loading...