Spring cache

Spring cache

DemoServiceImpl


@Configuration
//开启缓存
@EnableCaching
public class AppConfig {

}

AppConfig


@Service
public class DemoServiceImpl implements DemoService {

    @Autowired
    PersonRepository personRepository;

    @Override
    //无论怎样都会将方法的返回值放的缓存中
    @CachePut(value = "people", key = "#person.id")
    public Person save(Person person) {
        Person p = personRepository.save(person);
        System.out.println("为id、key为:"+p.getId()+"数据做了缓存");
        return p;
    }

    @Override
    //将一条或者多条数据从缓存中删除
    @CacheEvict(value = "people")//2
    public void remove(Long id) {
        System.out.println("删除了id、key为"+id+"的数据缓存");
        //这里不做实际删除操作
    }

    @Override
    //没有缓存则缓存,有缓存直接返回缓存
    @Cacheable(value = "people", key = "#person.id")//3
    public Person findOne(Person person) {
        Person p = personRepository.findOne(person.getId());
        System.out.println("为id、key为:"+p.getId()+"数据做了缓存");
        return p;
    }

}

你可能感兴趣的:(spring)