缓存
本地缓存
1)启动类增加注解 @EnableCaching // 开启缓存
2)在service层代码中增加注解,进行测试
本地缓存使用的是currentHashMap
```
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.ttzz.bean.Dog;
import com.ttzz.mapper.DataDemo;
@Service
/**
* @CacheConfig(cacheNames = {},cacheManager=AAAA,cacheResolver = {})
*/
public class DogService {
@Autowired
private DataDemo dataDemo;
/**
* @Cacheable:先在缓存中查找,如果没有该缓存,则创建,查询数据,放入缓存,并返回数据
* 参数:1)cacheNames/value:
* 2)key:
* 3)keyGenerator:
* 4)cacheManager:
* 5)condition:
* 6)unless:
* 7)sync:
*/
@Cacheable(value = "dog",/*cacheNames = ,keyGenerator = ,condition = ,unless = ,sync = true*/key = "#id")
public Dog getById(String id) {
return dataDemo.getById(id);
}
/**
* @CachePut: 先调用目标方法,然后调用缓存信息
*/
@CachePut(value = "dog",key="#dog.id")
public void save(Dog dog) {
dataDemo.save(dog);
}
@CachePut(value = "dog",key="#dog.id")
public void update(Dog dog) {
dataDemo.update(dog);
}
/**
* @CacheEvict:
* allEntries:删除整个缓存中的数据
* beforeInvocation:执行方法前删除还是执行方法后删除
*/
@CacheEvict(value = "dog" /* allEntries = true, beforeInvocation = true*/,key="#id")
public void delete(String id) {
dataDemo.delete(id);
}
/**
* @Caching:复合注解
* @Caching(
cacheable = {
@Cacheable(value = )
},
put = {
@CachePut()
}
)
*/
}
```