Spring Boot 菜鸟教程Java学习笔记Spring Boot

Spring Boot 菜鸟教程 17 Cache-缓存

2017-02-11  本文已影响292人  JeGe

缓存

Spring3.1开始引入了对Cache的支持

@CacheConfig

@CachePut

@CacheEvict

Spring Cache现有缺陷

业务逻辑实现类UserServiceImpl

package com.jege.spring.boot.data.jpa.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jege.spring.boot.data.jpa.entity.User;
import com.jege.spring.boot.data.jpa.repository.UserRepository;
import com.jege.spring.boot.data.jpa.service.UserService;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:业务层接口实现
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {
  @Autowired
  UserRepository userRepository;

  @Override
  @Cacheable()
  public Page<User> findAll(Pageable pageable) {
    return userRepository.findAll(pageable);
  }

  @Override
  @Cacheable()
  public Page<User> findAll(Specification<User> specification, Pageable pageable) {
    return userRepository.findAll(specification, pageable);
  }

  @Override
  @Transactional
  @CacheEvict(allEntries=true)
  public void save(User user) {
    userRepository.save(user);
  }

  @Override
  @Transactional
  @CacheEvict(allEntries=true)
  public void delete(Long id) {
    userRepository.delete(id);
  }

}

其他关联项目

源码地址

https://github.com/je-ge/spring-boot

如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。
**您的支持将鼓励我继续创作!谢谢! **

微信打赏微信打赏
支付宝打赏支付宝打赏
上一篇 下一篇

猜你喜欢

热点阅读