一.使用Ehcache
本文最后更新于 1544 天前,其中的信息可能已经有所发展或是发生改变。

1. pom

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

2. 创建 Ehcache 的配置文件

路径src/main/resources/hcahe.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <diskStore path="java.io.tmpdir"/>
    <!--maxElementsInMemory:内存中最大缓存对象数  
        maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大  
        eternal:Element是否永久有效,一但设置了,timeout将不起作用  
        overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中  
        timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大  
        timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大   
        diskPersistent:是否缓存虚拟机重启期数据  
        diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒  
        diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区  
        memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)
    -->

    <!--defaultCache:echcache的默认缓存策略  -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <!-- 自定义缓存策略 -->
    <cache name="users"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

3. 修改application.yml

spring:
  cache:
    ehcache:
      config: ehcache.xml

4. 修改启动类

@SpringBootApplication()
@MapperScan("com.yuyy.springbootdemo.mapper")
@EnableCaching
public class SpringBootDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }
}

5. 修改业务层

/**
 * @author yuyy
 * @date 2020/1/21 11:33
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    //@Cacheable:对当前查询的对象做缓存处理
    //value:选择缓存策略,可以自定义
    //key:配置缓存对象的key
    @Cacheable(value = "users",key = "#param.a")
    public User findUser(int id, TestParam param) {
        System.out.println(param);
        return userMapper.findUser(id);
    }
}

6. 测试

/**
 * @author yuyy
 * @date 2020/1/21 11:58
 */

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes= SpringBootDemoApplication.class)
public class UserServiceImplTest {

    @Autowired
    private UserService userService;
    @Test
    void findUser() {
        System.out.println(null==userService);
        TestParam param = TestParam.builder().a(1).b(0).c(0).build();
        TestParam param1 = TestParam.builder().a(0).b(1).c(0).build();
        TestParam param2 = TestParam.builder().a(0).b(0).c(1).build();
        System.out.println(userService.findUser(6, param));
        System.out.println(userService.findUser(6, param1));
        System.out.println(userService.findUser(6, param2));
    }
}

7. 结果

  • 只执行了两次sql,因为第二次和第三次的key相同,所以第三次使用的是缓存里的
    image

8. 清除缓存

  • UserServiceImpl
@Override
//清除缓存
//value:绑定缓存策略
@CacheEvict(value = "users",allEntries=true)
public void cacheEvict() {
}
  • Test
System.out.println(userService.findUser(6, param));
System.out.println(userService.findUser(6, param1));
userService.cacheEvict();
System.out.println(userService.findUser(6, param2));

image

作者:Yuyy
博客:https://yuyy.info
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇