springboot 缓存 Cacheable 集成redis

1. 开启缓存注解
@EnableCaching
@Configuration
public class RedisConfig {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Bean
	public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
		RedisTemplate redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(connectionFactory);

		GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		redisTemplate.setKeySerializer(stringRedisSerializer);
		redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
		redisTemplate.setHashKeySerializer(stringRedisSerializer);
		redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);

		return redisTemplate;
	}


2. 配置缓存使用redis
	@SuppressWarnings("rawtypes")
	@Bean
	public CacheManager cacheManager(RedisTemplate redisTemplate) {
		RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
		redisCacheManager.setDefaultExpiration(10 * 60); //设置缓存失效时间

		return redisCacheManager;
	}
}


3. 在方法上添加缓存注解
@Service
public class CacheService {
    // 添加缓存 ,下次再执行这个方法就从redis缓存中取数据
    //value 是指定业务名称,必须有,key是缓存key的名称 #name 表示是参数的name 
	@Cacheable(value = "names", key = "'names:' + #name") 
	public Hello hello(String name) {
		// select * from *** where name = ?
		Hello hello = new Hello();
		hello.setName(name);
		System.out.println("我被执行了:name=" + name);

		return hello;
	}

    //更新缓存 ,每次都会执行,更新数据到缓存中
	@CachePut(value = "names", key = "'names:' + #name")
	public Hello update(String name) {
		Hello hello = new Hello();
		hello.setName(name + "update");
		System.out.println("我被执行了update:name=" + name);

		return hello;
	}

    //删除缓存
	@CacheEvict(value = "names", key = "'names:' + #name")
	public Hello delete(String name) {
		Hello hello = new Hello();
		hello.setName(name + "delete");
		System.out.println("我被执行了delete:name=" + name);

		return hello;
	}
}

 

你可能感兴趣的:(redis)