redis 工具:https://redisdesktop.com/
redis 下载:https://redis.io/download 必须安装
<!-- redis缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
application.yml
redis:
host: 127.0.0.1
port: 端口号
password:
timeout: 6000
pool:
max-active: 20
max-wait: -1
max-idle: 8
min-idle: 0
RedisConfig
@Configuration
@EnableCaching
@AutoConfigureBefore(ListenerConfig.class)
public class RedisConfig {
//缓存管理器
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
cacheManager.setDefaultExpiration(10000);
return cacheManager;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template);
template.afterPropertiesSet();
return template;
}
private void setSerializer(StringRedisTemplate template){
@SuppressWarnings({ "rawtypes", "unchecked" })
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}
UserService
@Slf4j
@Service
@CacheConfig(cacheNames="app_user_info")
public class UserService {
@CachePut(key="#p0.userId")
public TUser update(TUser tUser){
return tUser;
}
}
@Cacheable将查询结果缓存到redis中,(key="#p0")指定传入的第一个参数作为redis的key。
@CachePut,指定key,将更新的结果同步到redis中
@CacheEvict,指定key,删除缓存数据,allEntries=true,方法调用后将立即清除缓存
…
应该还有其他注解的