多级缓存(javacache,redis,Elasticearch)

it2026-09-28  12

商品模块查看商品信息。 去java 缓存看看有没有数据。再然后去redis看看有没有数据,如果没有再去elasticsearch查找数据。 第一步 配置java缓存cache 导入依赖

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

配置缓存xml文件

<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <!-- 磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存 path:指定在硬盘上存储对象的路径 path可以配置的目录有: user.home(用户的家目录) user.dir(用户当前的工作目录) java.io.tmpdir(默认的临时目录) ehcache.disk.store.dir(ehcache的配置目录) 绝对路径(如:d:\\ehcache) 查看路径方法:String tmpDir = System.getProperty("java.io.tmpdir"); --> <diskStore path="java.io.tmpdir"/> <!-- defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理 maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象 eternal:代表对象是否永不过期 (指定true则下面两项配置需为0无限期) timeToIdleSeconds:最大的发呆时间 /秒 timeToLiveSeconds:最大的存活时间 /秒 overflowToDisk:是否允许对象被写入到磁盘 说明:下列配置自缓存建立起600秒(10分钟)有效 。 在有效的600秒(10分钟)内,如果连续120秒(2分钟)未访问缓存,则缓存失效。 就算有访问,也只会存活600秒。 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="600" overflowToDisk="true"/> <cache name="cache" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="600" overflowToDisk="true"/> </ehcache>

配置yml文件 启动类加上enableCaching 注解

方法上面加上@Cacheable 注解 value 缓存名,key 缓存里面的id。#id 跟你方法里面的id 一致 redUtil.get()方法。去redis 里面有没有这个商品。 没有就去elasticsearch 去找(skuFeginClient.info())。找到就取出来,也存入到redis 里面 skuFeginClient.info()通过fegin实现 fegin: ElasticSearch 里面的方法 controller 调用service方法 redis 依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.4.5.RELEASE</version> </dependency>

这样可以实现多级缓存了!

最新回复(0)