陕西优秀的企业门户网站建设,app 制作公司,人社通成都app下载,住房城乡建设管理网站一、springboot#xff08;如果没有配置#xff09;默认使用的是jvm缓存
1、Spring框架支持向应用程序透明地添加缓存。抽象的核心是将缓存应用于方法#xff0c;从而根据缓存中可用的信息减少执行次数。缓存逻辑是透明地应用的#xff0c;对调用者没有任何干扰。只要使用…一、springboot如果没有配置默认使用的是jvm缓存
1、Spring框架支持向应用程序透明地添加缓存。抽象的核心是将缓存应用于方法从而根据缓存中可用的信息减少执行次数。缓存逻辑是透明地应用的对调用者没有任何干扰。只要使用EnableCaching注释启用了缓存支持Spring Boot就会自动配置缓存基础结构。
2、在Spring Boot中默认情况下它会根据一定的顺序去侦测缓存提供者包括Generic、JCache(JSR-107)、EhCache 2.x、Hazelcast、Infinispan、Redis、Guava和Simple等 如果探测不到用的则是它会默认使用SimpleCacheConfiguration即使用ConcurrentMapCacheManager来实现缓存这是一种基于JVM内存的缓存。
具体代码案例
依赖 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-cache/artifactId/dependency
MyMathService:
package dev.farhan.movies.cache;import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;Component
public class MyMathService {Cacheable(piDecimals)public int computePiDecimal(int precision) throws InterruptedException {if (precision2){Thread.sleep(2000);return 45;}Thread.sleep(2000);return 23;}}
MyMathController类
package dev.farhan.movies.controller;import dev.farhan.movies.cache.MyMathService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;RestController
public class MyMathController {AutowiredMyMathService myMathService;GetMapping(/math)public void getMath() throws InterruptedException {System.out.println(myMathService.computePiDecimal(2));System.out.println(myMathService.computePiDecimal(89));}}结果访问localhost:8080/math
就会发现第一次响应用了4秒多 而第二次响应则是用了4毫秒明显走了缓存 二、我们比较常用的是redis的缓存
缓存抽象并不提供实际的存储而是依赖于org.springframework.cache.Cache和org.springframework.cache.CacheManager接口实现的抽象。
如果Redis可用且已配置则自动配置RedisCacheManager。通过设置spring.cache可以在启动时创建额外的缓存。cache-names属性和cache默认值可以通过spring.cache.redis配置。*属性。例如下面的配置创建了cache1和cache2缓存它们的生存时间为10分钟:
1、这里我们先配置一下redis
引入依赖
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId/dependency
第二步配置文件
spring:data:redis:host: #主机ippassword:cache:type: rediscache-names: cache1,cache2redis:time-to-live: 10m
然后启动项目并访问localhost:8080/math
观察redis里面 刚好存了piDecimals 可以对上 至于存的内容2和89则是它的参数