1.springboot版本:1.5.13.RELEASE
2.引入如下依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency>
3.配置CacheManager
-
GuavaCacheConfig
@Configuration public class GuavaCacheConfig { @Primary @Bean("guavaCacheManager") public CacheManager guavaCacheManager(){ GuavaCacheManager manager = new GuavaCacheManager(); manager.setCacheBuilder(CacheBuilder.newBuilder() .expireAfterAccess(10, TimeUnit.SECONDS) .maximumSize(1000)); return manager; } }
-
RedisCacheConfig
@Configuration public class RedisCacheConfig { @Autowired @Qualifier("springCacheRedisTemplate") RedisTemplate redisTemplate; @Bean("redisCacheManager") public CacheManager redisCacheManager(){ RedisCacheManager manager = new RedisCacheManager(redisTemplate); manager.setDefaultExpiration(10 * 60); // 设置过期时间30秒 return manager; } @Bean("springCacheRedisTemplate") public RedisTemplate redisTemplate(RedisConnectionFactory factory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); template.setKeySerializer(jackson2JsonRedisSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(jackson2JsonRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); template.setEnableTransactionSupport(true); return template; } }
3.使用缓存
在启动类上添加@EnableCaching注解开启缓存
@EnableCaching @SpringBootApplication @MapperScan("com.xys.springboot.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
4.使用缓存
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override @Cacheable( value = "user-cache", key = "#id", cacheManager = "guavaCacheManager") public User getUserByCache(Integer id) { return this.getById(id); } @Override @Cacheable( value = "user-cache", key = "'user:username:' + #username", cacheManager = "redisCacheManager") public User getUserByCache(String username) { return this.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username)); } }