springboot使用自带缓存


1、pom


    org.springframework.boot
    spring-boot-starter-cache
    2.1.6.RELEASE

2、main启动类加入@EnableCaching

import org.springframework.cache.annotation.EnableCaching;

@EnableCaching

3、自定义缓存key的命名规则

import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;

// 自定义缓存的 key生成
@Component
public class MyKeyGenerator implements KeyGenerator {
    @Override
    public Object generate(Object o, Method method, Object... objects) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(o.getClass().getSimpleName())
                .append("_")
                .append(method.getName())
                .append("_")
                .append(StringUtils.arrayToDelimitedString(objects, "_"));
        return stringBuffer.toString();
    }
}

4、在类上使用,访问类所有的方法都缓存

import com.pingan.domain.Student;
import com.pingan.mapper.StudentMapper;
import com.pingan.service.StudentService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

// 在类上加 @Cacheable 代表类下面所有的方法都缓存,cacheNames随便起,keyGenerator为自定义缓存key的bean
@Service("studentService")
@Cacheable(cacheNames = "StudentServiceCache",keyGenerator = "myKeyGenerator")
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentMapper studentMapper;

    @Override
    public Student queryById(Integer id) {
        return this.studentMapper.queryById(id);
    }
}

 在方法上使用,访问此方法才会缓存

@Cacheable(cacheNames = "StudentServiceCache",keyGenerator = "myKeyGenerator")
public Student queryById(Integer id) {
    return this.studentMapper.queryById(id);
}

5、在更新和插入的方法上加上  @CacheEvict 清空缓存

@CacheEvict(cacheNames = "StudentServiceCache",allEntries = true)
public Student insert(Student student) {
    this.studentMapper.insert(student);
    return student;
}

6、定时任务清缓存

通过定时任务去清缓存

    @Autowired
    private Demo01Controller demo01Controller;
    
    @Scheduled(cron = "0/4 * * * * *")
    public void test03() {
        demo01Controller.test02();    // test02方法上有注解 @CacheEvict
    }

ps: 本质利用了java类的内容,对tomcat会造成一定的压力

相关