Solo  当前访客:0 开始使用

spring通过注解操作缓存


一、注解使用
1、启动类上加@EnableCaching(proxyTargetClass = true)
2、service层加注解@CacheConfig(cacheNames = "name"),NAME为要缓存的对象
3、数据查询方法加上注解@Cacheable
4、清除缓存 调用方法加上注解@CacheEvict

二、demo

@Slf4j
@SpringBootApplication
@EnableCaching(proxyTargetClass = true)
public class SpringBucksApplication implements ApplicationRunner {
	@Autowired
	private CoffeeService coffeeService;

	public static void main(String[] args) {
		SpringApplication.run(SpringBucksApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		log.info("Count: {}", coffeeService.findAllCoffee().size());
		for (int i = 0; i < 10; i++) {
			log.info("Reading from cache.");
			coffeeService.findAllCoffee();
		}
		//coffeeService.reloadCoffee();
		log.info("Reading after refresh.");
		coffeeService.findAllCoffee().forEach(c -> log.info("Coffee {}", c.getName()));
	}
}
@Slf4j
@Service
@CacheConfig(cacheNames = "name")
public class CoffeeService {
    @Autowired
    private CoffeeRepository coffeeRepository;

    @Cacheable
    public List<Coffee> findAllCoffee() {
        return coffeeRepository.findAll();
    }

    @CacheEvict
    public void reloadCoffee() {
    }

}
0 0