zoukankan      html  css  js  c++  java
  • 【java】数据缓存之 EhCache缓存

    一、背景

    Java支持很多种缓冲方式:redis、guava、ehcache、jcache等。

    简单说明下redis和ehcache的区别:

      Redis:属于独立运行的程序,需要在服务器上安装运行,且使用第三方jar包对Jedis操作。因为是独立的,(在不考虑数据一致性问题的情况下)不同应用均可从Redis拿到相同的值。

      EhCache:与Redis明显不同的是,与应用程序绑定在一起,java应用活着,它就活着,且只能当前应用可查看缓存数据。

    二、先插一下(说点别的)

      先介绍下之前做过的一个项目,SpringBoot项目使用org.springframework.cache做缓存的一个例子。SpringBoot框架目的就是减少配置,“约定大于配置”,所以它已经为我们自动配置了多个CacheManager的实现,不需要再写XML文件。

      pom依赖配置:

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

      需要注意:在SpringBoot入口类中加@EnableCaching开启缓存。

     实现类

    import org.springframework.cache.annotation.CacheConfig;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    
    /**
     * @Author: liuxs
     * @Description:
     * @Date: Create in 14:45 2017/11/17.
     */
    @Service
    @CacheConfig(cacheNames = "testCache")
    public class CacheTestService {
    
        /**
         * 从缓存获取value,没有则插入
         * @param type
         * @return
         */
        @Cacheable(key = "#type")
        public String getCaches(String type) {
            return System.currentTimeMillis() + type;
        }
    
        /**
         * 清空缓存对应key的value
         * @param type
         */
        @CacheEvict(key = "#type")
        public void clearByType(String type) {
    
        }
    }

      测试类

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = CrmApplication.class)
    @WebAppConfiguration
    @Slf4j
    public class CacheTestServiceTest {
    
        @Autowired
        private CacheTestService cacheTestService;
    
        @Test
        public void getCaches() throws Exception {
            log.info("1st:" + cacheTestService.getCaches("type"));
            Thread.sleep(1000);
            log.info("2nd:" + cacheTestService.getCaches("type"));
            cacheTestService.clearByType("type1");
            Thread.sleep(2000);
            log.info("3rd:" + cacheTestService.getCaches("type"));
            cacheTestService.clearByType("type");
            Thread.sleep(3000);
            log.info("4th:" + cacheTestService.getCaches("type"));
        }
    }
  • 相关阅读:
    python基本数据类型操作
    ansible基本命令及剧本
    ansible模块及语法
    ansible主机组配置及秘钥分发
    ansible简介安装配置
    K8S使用---故障处理
    python脚本案例---备份单个目录
    telnet-server故障
    zabbix故障处理
    网站部署---LAMP环境部署PHP网站
  • 原文地址:https://www.cnblogs.com/liuxs13/p/7851348.html
Copyright © 2011-2022 走看看