二十四、Springboot整合Spring Cache及其使用案例

(一)Spring Cache简介
  Spring Cache核心接口:

org.springframework.cache.CacheManager
org.springframework.cache.Cache

  其中,CacheManager根据Cache的name管理所有的Cache,例如:

//cache-1就是某个Cache的name
Cache cache = cacheManager.getCache("cache-1");

  Spring Cache核心注解:

@Cacheable
@CacheEvict
@CachePut
@Caching
@CacheConfig

关于这些注解的具体使用参见Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用
(二)在Springboot中使用Spring Cache
1、添加依赖

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

2、编码方式配置Spring Cache核心类CacheManager,同时激活缓存

/**
 * 激活缓存:@EnableCaching
 * 备注:要想使用@Cacheable这些缓存注解,必须激活缓存
 */
@Configuration
@EnableCaching
public class CacheConfiguration {
    @Bean
    public CacheManager cacheManager(){
        /**
         * 这里面的缓存名,是和后面@Cacheable(cacheNames = CACHE_NAME)绑定使用的
         */
        return new ConcurrentMapCacheManager("cache-1", "cache-user");
    }
}

3、仓储接口及其实现
仓储接口

/**
 * 一般用作父类的repository,有这个注解,spring不会去实例化该repository:@NoRepositoryBean
 */
@NoRepositoryBean
public interface UserRepository {
    boolean save(User user);
    User findUser(Long id);
}

仓储实现

@Repository
public class UserRepositoryImpl implements UserRepository {
    private static final String CACHE_NAME = "cache-user";
    private Map userMap = new HashMap<>();
    @Override
    public boolean save(User user) {
        return userMap.putIfAbsent(user.getId(), user) == null;
    }

    /**
     * 对该方法的返回值进行缓存:@Cacheable
     */
    @Cacheable(cacheNames = CACHE_NAME)
    @Override
    public User findUser(Long id) {
        User user = userMap.get(id);
        return user;
    }
}

4、测试

@RestController
@RequestMapping("/user")
public class UserController {
    private UserRepository userRepository;
    @Autowired
    public UserController(UserRepository userRepository){
        this.userRepository = userRepository;
    }
    @PostMapping
    public boolean save(@RequestBody User user){
        return userRepository.save(user);
    }
    @GetMapping("/{id}")
    public User findUser(@PathVariable Long id){
        return userRepository.findUser(id);
    }
}

你可能感兴趣的:(Spring,Boot,从入门到放弃)