暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

springboot与ehcache简单用法

技术漂流客 2020-06-17
315

最先来一波redis图片


springboot与ehcache

最近听领导说要实现本地缓存与redis缓存配合使用,提高缓存查询速度问题,领导提起ehcache,自从没有使用过hibernate之后,就没有关注该缓存了,今再拾起研究一番。

引入ehcache

  1. <dependency>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-cache</artifactId>

  4. </dependency>

  5. <dependency>

  6. <groupId>net.sf.ehcache</groupId>

  7. <artifactId>ehcache</artifactId>

  8. </dependency>

添加echache.xml

  1. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd">

  2. <diskStore path="java.io.tmpdir"/>

  3. <defaultCache

  4. maxElementsInMemory="10000"

  5. eternal="false"

  6. timeToIdleSeconds="120"

  7. timeToLiveSeconds="120"

  8. maxElementsOnDisk="10000000"

  9. diskExpiryThreadIntervalSeconds="120"

  10. memoryStoreEvictionPolicy="LRU">

  11. <persistence strategy="localTempSwap"/>

  12. </defaultCache>

  13. <cache name="users"

  14. maxElementsInMemory="10000"

  15. eternal="false"

  16. timeToIdleSeconds="120"

  17. timeToLiveSeconds="120"

  18. maxElementsOnDisk="10000000"

  19. diskExpiryThreadIntervalSeconds="120"

  20. memoryStoreEvictionPolicy="LRU">

  21. <persistence strategy="localTempSwap"/>

  22. </cache>

  23. </ehcache>

ehcache配置简介

  • diskStore

这个是磁盘存储路径,当内存缓存满了的时候,就会往这里面放,java.io.tmdir是操作系统缓存的临时目录,不同操作系统缓存目录不一样

  • maxElementsInMemory

内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况 1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中 2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素

  • overflowToDisk

内存不足时,是否启用磁盘缓存

  • eternal

缓存中对象是否永久有效

  • timeToIdleSeconds

缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除

  • timeToLiveSeconds

缓存数据的总的存活时间(单位:秒),仅当eternal=false时使用,从创建开始计时,失效结束

  • maxElementsOnDisk

磁盘缓存中最多可以存放的元素数量,0表示无穷大

  • diskExpiryThreadIntervalSeconds

磁盘缓存的清理线程运行间隔,默认是120秒

  • memoryStoreEvictionPolicy

内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存 共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)

application.yml配置

  1. spring:

  2. cache:

  3. type: ehcache

  4. ehcache:

  5. config: classpath:ehcache.xml

缓存操作

缓存的实体对象都必须实现序列化接口(java.io.Serializable)

UserInfo缓存实体对象

  1. package com.example.demo.cache;

  2. import com.alibaba.fastjson.JSON;

  3. import java.io.Serializable;


  4. /**

  5. * @author 飘零的叶子

  6. */

  7. public class UserInfo implements Serializable {

  8. private static final long serialVersionUID = 2296172282217381086L;

  9. private Long id;

  10. private String username;

  11. private String password;

  12. public Long getId() {

  13. return id;

  14. }

  15. public void setId(Long id) {

  16. this.id = id;

  17. }

  18. public String getUsername() {

  19. return username;

  20. }

  21. public void setUsername(String username) {

  22. this.username = username;

  23. }

  24. public String getPassword() {

  25. return password;

  26. }

  27. public void setPassword(String password) {

  28. this.password = password;

  29. }

  30. @Override

  31. public String toString() {

  32. return JSON.toJSONString(this);

  33. }

  34. }

CacheService缓存操作服务

  1. package com.example.demo.cache;

  2. import org.springframework.cache.annotation.CacheEvict;

  3. import org.springframework.cache.annotation.CachePut;

  4. import org.springframework.cache.annotation.Cacheable;

  5. import org.springframework.stereotype.Component;

  6. import java.util.ArrayList;

  7. import java.util.List;

  8. import java.util.Map;

  9. import java.util.Set;

  10. import java.util.concurrent.ConcurrentHashMap;


  11. /**

  12. * @author 飘零的叶子

  13. */

  14. @Component

  15. public class CacheService {

  16. private static final ConcurrentHashMap<Long, UserInfo> USER_CACHE = new ConcurrentHashMap<>(64);

  17. private static final String CACHE_NAME = "users";

  18. @CachePut(value = CACHE_NAME, key = "#user.id")

  19. @CacheEvict(value = CACHE_NAME,allEntries = true)

  20. public UserInfo save(UserInfo user) {

  21. System.out.println("保存数据库啦~~~~~ user = " + user);

  22. USER_CACHE.put(user.getId(), user);

  23. return user;

  24. }

  25. @CacheEvict(value = CACHE_NAME,allEntries = true)

  26. public boolean delete(Long id) {

  27. UserInfo userInfo = USER_CACHE.get(id);

  28. System.out.println("删除数据啦 id = " + id + ", userInfo = " + userInfo);

  29. USER_CACHE.remove(id);

  30. return true;

  31. }

  32. @CachePut(value = CACHE_NAME, key = "#user.id")

  33. @CacheEvict(value = CACHE_NAME,allEntries = true)

  34. public UserInfo update(UserInfo user) {

  35. UserInfo old = USER_CACHE.get(user.getId());

  36. System.out.println("更新缓存 user= " + user + ",old = " + old);

  37. USER_CACHE.put(user.getId(), user);

  38. return user;

  39. }

  40. @Cacheable(value = CACHE_NAME, key = "#id")

  41. public UserInfo findOne(Long id) {

  42. UserInfo user = USER_CACHE.get(id);

  43. System.out.println("查询用户信息拉~~~ user = " + user + ",id = " + id);

  44. return user;

  45. }

  46. @Cacheable(value = CACHE_NAME)

  47. public List<UserInfo> findAll() {

  48. System.out.println("查询用户列表啦....");

  49. Set<Map.Entry<Long, UserInfo>> entries = USER_CACHE.entrySet();

  50. List<UserInfo> userList = new ArrayList<>();

  51. for (Map.Entry<Long, UserInfo> entry : entries) {

  52. userList.add(entry.getValue());

  53. }

  54. return userList;

  55. }

  56. }

UserInfoController接口操作类

  1. package com.example.demo.controller;

  2. import com.example.demo.cache.CacheService;

  3. import com.example.demo.cache.UserInfo;

  4. import org.springframework.web.bind.annotation.*;

  5. import javax.annotation.Resource;

  6. import java.util.List;

  7. /**

  8. * @author 飘零的叶子

  9. */

  10. @RestController

  11. @RequestMapping("/userInfo")

  12. public class UserInfoController {

  13. @Resource

  14. private CacheService cacheService;

  15. @PostMapping("/save")

  16. public UserInfo save(@RequestBody UserInfo user) {

  17. return cacheService.save(user);

  18. }

  19. @GetMapping("/delete/{id}")

  20. public boolean delete(@PathVariable("id") Long id) {

  21. return cacheService.delete(id);

  22. }

  23. @GetMapping("/update")

  24. public UserInfo update(@RequestBody UserInfo user) {

  25. return cacheService.update(user);

  26. }

  27. @GetMapping("/findOne/{id}")

  28. public UserInfo findOne(@PathVariable("id") Long id) {

  29. return cacheService.findOne(id);

  30. }

  31. @GetMapping("/findAll")

  32. public List<UserInfo> findAll() {

  33. return cacheService.findAll();

  34. }

  35. }

启用注解

在Springboot启动类上添加启用缓存注解

@EnableCaching

缓存注解名称解释

  • @CachePut

保存操作,会将对象信息写入缓存 如: @CachePut(value = CACHE_NAME, key = "#user.id") 1) value为缓存名称 2) key为缓存的key,支持spring el表达式

  • @CacheEvict(value = CACHE_NAME,allEntries = true)

删除缓存操作,allEntries 设置为true则将相关缓存都清除

  • @Cacheable(value = CACHE_NAME, key = "#id")

根据key查询缓存信息

  • @Cacheable(value = CACHE_NAME)

查询所有缓存信息

完结

使用ehcache主要看中其内存缓存,与redis相比其优势就是省去了socket的数据通信交互,直接从内存中获取数据,会比redis获取数据有一定的速度优势;但是ehcache对分布式支持的不太好,在微服务分布式环境下,会造成各自应用的缓存数据不一致。但是对于领导要求的ehcache与redis相结合,刚好满足热数据直接从缓存中拿取的功能,提升调度服务的响应速度。


文章转载自技术漂流客,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论