1.导入pom依赖
项目依赖于spring boot parent 2.2.2.RELASE
org.springframework.boot
spring-boot-starter-data-redis
org.apache.commons
commons-pool2
2.配置相关设置 application.yml
spring:
redis:
host: localhost
port: 6379
database: 0
password:
lettuce:
pool:
max-active: 20
max-wait: -1
max-idle: 8 #空闲最大连接数
min-idle: 0
3.编写config类 redis的缓存序列方案 (redis的数据是我们常见的jsong格式)
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
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.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
import java.time.Duration;
@Configuration
@EnableCaching
@Slf4j
public class RedisConfig {
@Bean
public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory){
RedisTemplate<String,Serializable> redisTemplate=new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@Bean
public CacheManager cacheManager(LettuceConnectionFactory connectionFactory){
RedisCacheConfiguration conf=RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
.disableCachingNullValues();
RedisCacheManager cacheManager=RedisCacheManager.builder(connectionFactory)
.cacheDefaults(conf)
.build();
return cacheManager;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
4.在代码中使用reids缓存 @Cacheable
@Cacheable(value = "index",key = "'getTopTeacher'")
@Override
public List<Teacher> getTopTeacher() {
QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
teacherQueryWrapper.orderByDesc("sort");
teacherQueryWrapper.last("limit 4");
return teacherMapper.selectList(teacherQueryWrapper);
}