1. 程式人生 > 其它 >springboot使用自帶快取

springboot使用自帶快取

1、main啟動類加入@EnableCaching

import org.springframework.cache.annotation.EnableCaching;

@EnableCaching

2、自定義快取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();
    }
}

3、在類上使用,訪問類所有的方法都快取

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);
}

4、在更新和插入的方法上加上 @CacheEvict清空快取

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