1.自己编写的缓存
启动类时,把第一次读取到的数据加载到静态缓存中
@SpringBootApplication
public class DuckApplication {
public static void main(String args[]){
SpringApplication application = new SpringApplication(DuckApplication.class);
ApplicationContext ctx = application.run(args);
Cache.init(ctx);
}
}
自定义缓存类:
public class Cache {
private static final Logger LOGGER = LoggerFactory.getLogger(Cache.class);
private static ApplicationContext ctx;
//把读取到的数据缓存到map中
public static Map<String, List<Bank>> cache_bank = new HashMap<>();
public static void init(ApplicationContext applicationContext){
ctx = applicationContext;
initBanks();
}
public static void initBanks() {
DuckMapper duckMapper = (DuckMapper) ctx.getBean("duckMapper");
List<Bank> banks = duckMapper.selectBanks();
cache_bank.put("banksInfo", banks);
LOGGER.info("banks信息缓存完成!!");
}
public static List get(String key){
return cache_bank.get(key);
}
2.spring的三个缓存注解@CachePut,@CacheEvict,@Cacheable
2.1 @CachePut缓存新增的或更新的数据到缓存,其中缓存名字是 people 。数据的key是person的id
@CachePut(value = "people", key = "#person.id") public Person save(Person person) {}
2.2 @CacheEvict 从缓存people中删除key为id 的数据
@CacheEvict(value = "people") publicvoidremove(Long id) {}
2.3 @Cacheable缓存key为person 的id 数据到缓存自定义缓存名称“mycache” 中,如果没有指定key则方法参数作为key保存到缓存中。
@Cacheable(value = "mycache", key = "#person.id")
public Person findOne(Person person) {}
使用这些注解需要在启动配置类上加 @EnableCaching 来识别缓存注解
@CachePut缓存新增的或更新的数据到缓存,其中缓存名字是 people 。数据的key是person的id@CachePut(value = "people", key = "#person.id")
总结:
如果是不变的查询的数据是不经查变动的,适合用@Cacheable
如果是经常有新增操作的数据,且还要加入缓存查询,用@CachePut