Ehcache大杂烩

栏目: 数据库 · 发布时间: 5年前

内容简介:文章首发:
<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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

数据挖掘技术

数据挖掘技术

[美]MichaelJ.A.B / 别荣芳、尹静、邓六爱 / 机械工业 / 2006-7 / 49.00元

本书是数据挖掘领域的经典著作,数年来畅销不衰。全书从技术和应用两个方面,全面、系统地介绍了数据挖掘的商业环境、数据挖掘技术及其在商业环境中的应用。自从1997年本书第1版出版以来,数据挖掘界发生了巨大的变化,其中的大部分核心算法仍然保持不变,但是算法嵌入的软件、应用算法的数据库以及用于解决的商业问题都有所演进。第2版展示如何利用基本的数据挖掘方法和技术,解决常见的商业问题。 本书涵盖核心的数......一起来看看 《数据挖掘技术》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

MD5 加密
MD5 加密

MD5 加密工具