SpringBoot-整合第三方缓存技术

整合第三方缓存技术 :

缓存 : cache

  • 缓存是一种介于数据永久存储介质与数据应用之间的数据临时存储介质
  • 使用缓存可以有效的减少低速数据读取过程的次数 (例如磁盘IO) , 提高系统性能

缓存使用 :

  • 启用缓存
  • 设置进入缓存的数据
  • 设置读取缓存的数据

(1)首先 : 导入依赖坐标

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

(2)在主启动类上加一个注解 :

@EnableCaching //开启缓存功能

(3)在要使用缓存的service的方法上添加一个注解

@Cacheable(value = "cacheSpace",key = "#id")
//value : 指定一个缓存空间 , 自定义的
//key : 指定缓存数据的id值 , 注意要加一个 #
被这个注解修饰的方法 , 在接收请求之后 , 会先去这个缓存空间中查找是否有对应的key的值 , 
如果有 , 就从缓存空间中获取值 , 如果没有 , 在进行dao层的访问 , 并把查询结果存到这个缓存空间中
@CachePut(value = "cacheSpace",key = "#id")
//这个注解是每次操作之后都往里边放 , 但是再次执行这个操作的时候, 并不会从缓存中期取

SpringBoot缓存支持的技术 :

  • Generic
  • JCache
  • Ehcache
  • Hazelcast
  • Infinispan
  • Couchbase
  • Redis
  • Caffenine
  • Simple(默认的)
  • memcached

(1)切换Ehcache缓存技术

  • 导入坐标:

  • <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
    
  • 编写对应的配置

  • spring:
    cache:
        type: ehcache
        ehcache:
          config: ehcache.xml
    
  • 但是到这里还不行 ,Ehcache是一个Sping体系之外的技术 , 并不能直接配置 , 还要有一个配置文件 ehcache.xml

  • <!--默认缓存策略-->
    <!--
    eternal: 是否永久保存,设置为true则不会被清除,此时与timeout冲突,通常设置为false
    diskPersistent : 是否开启磁盘持久化
    maxElementsInMemory : 最大缓存数量
    overflowToDisk : 超过最大缓存数量是否持久化到磁盘
    timeToIdleSeconds : 最大不活动间隔 , 设置过长缓存容易溢出 , 设置过短无效果 , 可用于记录时效性数据 , 例如验证码
    timeToLiveSeconds : 最大存活时间 
    memoryStoreEvictionPolicy : 缓存清除策略
    -->
    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:moMamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
             updateCheck="false">
        <diskStore path="D:\Memcached缓存\memcached-amd64"/>
        <defaultCache
            eternal="false"
            diskPersistent="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            timeToIdleSeconds="60"
            timeToLiveSeconds="60"
            memoryStoreEvictionPolicy="LRU"/>
    
        <!--指定对应的缓存空间的name , 管理不同的缓存空间的策略-->
        <cache 
            name="ceshi"
            eternal="false"
            diskPersistent="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            timeToIdleSeconds="60"
            timeToLiveSeconds="60"
            memoryStoreEvictionPolicy="LRU"/>
    
    </ehcache>
    

缓存数据淘汰策略

  • volatile-lru : 挑选最近最少使用的数据淘汰
  • volatile-lfu : 挑选最近使用次数最少的数据淘汰
  • volatile-ttl : 挑选将要过期的数据淘汰
  • volatile-random : 任意选择数据淘汰

(2)切换Redis缓存技术

  • 导入对应的依赖坐标

  • 配置redis属性 :

  • spring:
      cache:
        type: redis #设置缓存机制使用redis
        redis:
          use-key-prefix: true #设置key值是否带前缀 , 降低key名字重复的概率
          cache-null-values: false #设置是否缓存空值
          key-prefix: aa #指定key的前缀
          time-to-live: 10s #指定缓存的失效时间 , 可以设置自定义
    
      redis: #redis的基础
        host: localhost
        port: 6379
    

(3)切换Memcached缓存技术

  • Memcached Client for Java : 最早期客户端 , 稳定可靠 , 用户群广
  • SpyMemcached : 效率更高
  • Xmemcached : 并发处理更好

SpringBoot未提供对memcache的整合 , 需要使用硬编码的方式实现客户端初始化管理

  • 首先创建一个配置类 , 将这个对象交给Springboot进行管理

  • 编写yml文件 , 将配置写进去 , 然后通过加载配置文件中的内容 , 将配置设置到配置类中

@Component
@ConfigurationProperties(prefix = "memcached")
@Data
public class XMemcachedProperties {
    private String servers;
    private int poolSize;
    private long opTimeout;
}

//------------读取配置文件中配置的属性 
@Configuration
public class XMemecachedConfig {

    @Autowired
    private XMemcachedProperties xMemcachedProperties;

    @Bean
    public MemcachedClient getMemcachedCLient() throws IOException {
        MemcachedClientBuilder memcachedClientBuilder = new XMemcachedClientBuilder(xMemcachedProperties.getServers());
        memcachedClientBuilder.setConnectionPoolSize(xMemcachedProperties.getPoolSize());
        memcachedClientBuilder.setOpTimeout(xMemcachedProperties.getOpTimeout());
        MemcachedClient build = memcachedClientBuilder.build();
        return build;
    }
}
 //以下是在springboot中使用xmemcached
    @Autowired
    private MemcachedClient memcachedClient;

    @Override
    public String sendCodeToSMS(String tele) {
        String code = smsUtil.generator(tele);
        try {
            memcachedClient.set(tele, 0, code);
            //设置缓存的key值 , 缓存失效时间 , 缓存的value值
        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }

    //取出内存中的验证码与传递过来的验证码对比,如果相同,返回true
    @Override
    public boolean sss(SMSCode smsCode) {
        String code = null;
        try {
            code = memcachedClient.get(smsCode.getTele().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return smsCode.getCode().equals(code);
    }

(4)切换jetcache技术

这个是阿里提供的高性能的缓存技术 , 是对SpringCache进行封装 , 在原有功能基础上实现了多级缓存 , 缓存统计 ,自动刷新 , 异步调用 , 数据报表等功能

jetCache技术设定了本地缓存与远程缓存的多级缓存解决方案

  • 本地缓存(local)
    • LinkedHashMap
    • Caffeine
  • 远程缓存(remote)
    • Redis
    • Tair

使用 :

  • 导入对应的坐标 :
<!-- https://mvnrepository.com/artifact/com.alicp.jetcache/jetcache-starter-redis -->
<dependency>
    <groupId>com.alicp.jetcache</groupId>
    <artifactId>jetcache-starter-redis</artifactId>
    <version>2.6.2</version>
</dependency>
  • 编写配置 :
jetcache:
#远程缓存
  remote:
    default:
      type: redis
      host: localhost
      port: 6379
      poolconfig:
        maxTotal: 50
  • 在主启动类中设置一个注解

  • @EnableCreateCacheAnnotation
    
  • 在使用缓存的地方告诉Spring要使用缓存

  • @CreateCache(area = "sms" ,name = "jetCache",expire = 3600,timeUnit = TimeUnit.SECONDS)
        //告诉Spring使用缓存 , 缓存的key的前缀为jetCache , 失效时间为3600s , area指定使用配置文件中的那个配置
        private Cache<String,String> jetcache;
    

使用本地缓存:

#远程方案使用的是remote
#本地方案使用的是localhost
jetcache:
  localhost:
    default:
      type: linkedhashmap
      keyConvertor: fastjson
      #为了减轻负担 , 要将key的类型转换为String , 这个是指定转换的方式 , 使用阿里云的fastjson
  • 在方法上设置使用本地缓存:

  • @CreateCache(area = "sms" ,name = "jetCache",expire = 3600,timeUnit = TimeUnit.SECONDS ,cacheType = CacheType.LOCAL)
    //告诉Spring使用缓存 , 缓存的key的前缀为jetCache , 失效时间为3600s , area指定使用配置文件中的那个配置
    private Cache<String,String> jetcache;
    
类型值含义
CacheType.LOCAL使用本地缓存方案
CacheType.REMOTE使用远程方案(默认方案)
CacheType.BOTH两种方案都使用

开启方法缓存 :

  • 需要在主启动类上设置一个注解

  • //开启方法注解缓存 , 可以使用数组进行多个配置 , 
    //这个是指定使用方法缓存的包的名称
    @EnableMethodCache(basePackages = "com.sichen.xxx")
    
  • 在方法上添加一个注解

  • @Cached(name = "book_",key = "#tele",expire = 3600)
    //指定缓存的前缀名 , 指定缓存的key值 , 
    

注意 : 在这里首先要在yml文件中指定

keyConvertor: fastjson
#设置数据转换方案
valueEncode: java
#设置值在进行转换的时候转为java对象
valueDecode: java
#设置值在转回来的时候也转为java对象

当执行修改操作的时候 , 要在上边加一个注解

@CacheUpdate(name="book_" , key="#book.id" , value="#book")
//指定前缀 , 指定修改的key ,这里是指book中的id这个值 , 指定修改后的value值

当执行删除操作的时候 ,

@CacheInvalidate(name="book_" , key="#id")
//指定删除的缓存的key值

设置缓存多久刷新一次 :

解决多个机器之间使用缓存数据不同步的问题 :

@CacheRefresh(refresh = 10)
    //设置10秒刷新一次

这个注解一般不要使用 , 太消耗性能了


开启统计数据的功能 : (可以查看缓存的性能)

在配置文件中设置一个属性 :

statIntervalMinutes: 1 
#单位为分钟

image-20220409102922277

get统计的是请求的次数 , hit统计的是命中的次数 , fail统计的是命中失败的信息 , expire统计的是过期的


(5)使用j2Cache框架

j2cache是一个缓存整合框架 , 可以提供缓存的整合方案 , 使各种缓存搭配使用 , 自身不提供给缓存功能

  • 导入对应的依赖坐标

  • <dependency>
        <groupId>net.oschina.j2cache</groupId>
        <artifactId>j2cache-spring-boot2-starter</artifactId>
        <version>2.8.0-release</version>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
    

j2Cache框架推荐使用的就是redis缓存技术

所以内置的就有redis的依赖坐标

  • 配置主配置文件:

  • j2cache:
      config-location: j2cache.properties
    #指定j2cache的配置文件名
    
  • 配置配置文件:

  • #一级缓存
    j2cache.L1.provider_class = ehcache
    #指定ehcache的配置文件的名称
    ehcache.configXml = ehcache.xml
    
    #二级缓存
    #指定
    j2cache.L2.provider_class = net.oschina.j2cache.cache.support.redis.SpringRedisProvider
    #这里下边的前缀是什么, 后边的值就需要写什么
    j2cache.L2.config_section = redis
    redis.host = localhost:6379
    
    #一级缓存中的数据如何到达二级缓存
    j2cache.broadcast = net.oschina.j2cache.cache.support.redis.SpringRedisPubSubPolicy
    
  • 编写实现代码

  • //导入对象
    @Autowired
    private CacheChannel cacheChannel
    
    //------------------
    //使用 
    cacheChannel.set("sms",tele,code);
    //存数据 , 设置域名 sms , key值 : tele , value值 :code
    
    //取数据
    cacheChannel.get("sms",sms.Code.getTele()).asString();
    
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值