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
- SpringBoot2.0之后默认使用 lettuce 作为操作 redis 的客户端,lettuce 使用 Netty 进行网络通信
- lettuce 的 bug 导致 Netty 堆外内存溢出, Netty 如果没有指定对外内存 默认使用 JVM 设置的参数
可以通过 -Dio.netty.maxDirectMemory 设置堆外内存
解决方案:不能仅仅使用 -Dio.netty.maxDirectMemory 去调大堆外内存- 升级 lettuce 客户端 2. 切换使用 jedis
RedisTemplate 对 lettuce 与 jedis 均进行了封装 所以直接使用 详情见:RedisAutoConfiguration 类
- 升级 lettuce 客户端 2. 切换使用 jedis
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每台都进入数据库拿过一次数据!这个本地锁的问题一样,只能锁住当前进程!!!