分布式缓存-cache

1.导入依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
		 <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

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

我这里的cache是使用Redis做数据缓存,所以这里需要导入redis的依赖;
注意:产生堆外内存溢出 OutOfDirectMemoryError

  1. SpringBoot2.0之后默认使用 lettuce 作为操作 redis 的客户端,lettuce 使用 Netty 进行网络通信
  2. lettuce 的 bug 导致 Netty 堆外内存溢出, Netty 如果没有指定对外内存 默认使用 JVM 设置的参数
    可以通过 -Dio.netty.maxDirectMemory 设置堆外内存
    解决方案:不能仅仅使用 -Dio.netty.maxDirectMemory 去调大堆外内存
    1. 升级 lettuce 客户端 2. 切换使用 jedis
      RedisTemplate 对 lettuce 与 jedis 均进行了封装 所以直接使用 详情见:RedisAutoConfiguration 类

2.配置properties

#缓存的名称集合,多个采用逗号分割
spring.cache.cache-names=
#缓存的类型,官方提供了很多,这里使用redis
spring.cache.type=redis
指#redis中缓存超时的时间,默认60000ms
spring.cache.redis.time-to-live=3600000
#缓存数据key是否使用前缀,默认是true
spring.cache.redis.use-key-prefix=true
#缓存数据key的前缀,在上面的配置为true时有效,
spring.cache.redis.key-prefix=
#是否缓存null数据,默认是false
spring.cache.redis.cache-null-values=true

这里redis的配置就不多说了

3.启动类开启缓存

@EnableCaching
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application .class, args);
    }
}

4.实现类上加缓存

@Service
public class TestImpl implements TestService {

	//模拟数据库的数据
    static List<String> l=new ArrayList<>();
    static {
        for (int i=0;i<100;i++){
            l.add(String.valueOf(i));
        }
    }

    @Override
    public List<String> getDataList() {
        return l;
    }


    @Override
    @Cacheable(value = {"cache"}, key = "#root.methodName")//这里取值是要注意如果key的值是固定的那么需要带上''好
    //将返回值作为cache缓存区的缓存数据缓存数据的key为当前方法名
    public List<String> getCacheDataList() {
        return l;
    }

    //多个缓存操作
    // @Caching(evict = {
    //         @CacheEvict(value = "cache", key = "'cache'"),//key是固定的值是需要加''号
    //         @CacheEvict(value = "cache", key = "'cacheJson'")//删除cache缓存分区中key为cacheJson的缓存数据
    // })
    @CacheEvict(value = "cache", allEntries = true)//allEntries会删除整个缓存分区cache的所有数据
    //这里如果不想删除所有的话可以@CacheEvict(value = "cache", key = "'xxx'")
    // 删除cache缓存分区中key为xxx的缓存数据
    @Override
    public void updateCacheDataList() {
        l.add(String.valueOf(101));
    }
}

@Cacheable
该注解作用是标识这个方法返回值将会被缓存;
需要注意 condition 和 unless ,它们都是条件判断参数:
condition:在调用方法之前进行判断,所以不能将方法的结果值作为判断条件;
unless:在调用方法之后进行判断,此时可以拿到方法放回值作为判断条件。
所以依赖方法返回值作为是否进行缓存的操作必须使用 unless 参数,而不是 condition

@CachePut
将方法返回值更新当前缓存

@CacheEvict
清空当前缓存

其他的就自己琢磨去吧

查看效果
在这里插入图片描述
这里的缓存值有问题,这是按照java序列化的结果,这里如果存在别的系统使用的话需要缓存JSON
这里重发发送请求也不会查询数据库,只要redis缓存中存在那么就不会查询数据库

设置缓存格式为JSON
创建配置类

package com.test.demo.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
* @description: Cache核心配置
* @author TAO
* @date 2020/7/17 11:09
*/
@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class MyCacheConfig {

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //这里是采用一个链式传递的,所以需要先将默认的Cache配置得到,然后在加入我们的配置
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //自定义缓存数据格式为JSON
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        //properties中的值会映射到CacheProperties类中
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();

        //CacheProperties类中取出我们自己配置的值,从新添加到配置中
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}

再次运行
清空redis缓存
在这里插入图片描述
搞定!!!

看看分布式环境下运行的情况

启动三台测试服务13001/13002/13003
使用Gateway做网关代理,使用Jmeter模拟并发,清空缓存数据

.13001
在这里插入图片描述
13002
在这里插入图片描述
13003
在这里插入图片描述
貌似好像出问题了,这里Jmeter模拟10000的请求,缓存好像没拦住!!!

开启同步
修改getCacheDataList方法的@Cacheable注解,添加sync
在多线程环境下,某些操作可能使用相同参数同步调用。默认情况下,缓存不锁定任何资源,可能导致多次计算,而违反了缓存的目的。对于这些特定的情况,属性 sync 可以指示底层将缓存锁住,使只有一个线程可以进入计算,而其他线程堵塞,直到返回结果更新到缓存中。

@Override
    @Cacheable(value = {"cache"}, key = "#root.methodName",sync = true)//sync 标识同步的方式
    //将返回值作为cache缓存区的缓存数据缓存数据的key为当前方法名
    public List<String> getCacheDataList() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("查询数据库");
        return l;
    }

查看效果
13001
在这里插入图片描述
13002
在这里插入图片描述
13003
在这里插入图片描述
加上sysc就能解决高并发所产生的问题了,这个sysc底层采用的是synchronized代码开实现的,但是这也存在问题也就是和本地锁一样的问题,理想的结果是13001/13002/13003中只有一台进入数据库中拿数据,其他的所有的请求都从缓存中拿,而上面的运行结果确实13001/13002/13003每台都进入数据库拿过一次数据!这个本地锁的问题一样,只能锁住当前进程!!!
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员劝退师-TAO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值