轻松搞定数据缓存

版权声明:转载请注明出处 https://blog.csdn.net/cowbin2012/article/details/85220033

缓存可以缓解数据库访问的压力,Spring自身不提供缓存的存储实现,需要借助第三方,比如JCache、EhCache、Hazelcast、Redis、Guava等。Spring Boot可以自动化配置合适的缓存管理器(CacheManager),默认采用的是ConcurrentMapCacheManager(java.util.concurrent.ConcurrentHashMap)

添加 spring-boot-starter-cache 依赖

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-cache</artifactId>  
</dependency> 

开启缓存功能

@Configuration  
@EnableCaching  
public class CacheConfig {  
  
}

缓存数据

对于缓存的操作,主要有:@Cacheable、@CachePut、@CacheEvict。

@Cacheable

Spring 在执行 @Cacheable 标注的方法前先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,执行该方法并将方法返回值放进缓存。  参数: value缓存名、 key缓存键值、 condition满足缓存条件、unless否决缓存条件

@CachePut

和 @Cacheable 类似,无论缓存有没有数据,执行该方法并将方法返回值放进缓存, 主要用于数据新增和修改方法。

@CacheEvict

方法执行成功后会从缓存中移除相应数据。  参数: value缓存名、 key缓存键值、 condition满足缓存条件、 unless否决缓存条件、 allEntries是否移除所有数据(设置为true时会移除所有缓存)

@Component
@Slf4j
public class CacheUtil {
​
    @Autowired
    User user;
​
    @Cacheable(value = "user", key = "#user.name")
    public User getUser(User user){
        log.info("get user");
        return user;
    }
​
    @CachePut(value = "user", key = "#user.name")
    public User saveUser(User user){
        log.info("save user");
        return user;
    }
​
    @CacheEvict(value = "user", key = "#name") // 移除指定key的数据
    public void deleteUser(String name){
        log.info("delete user");
    }
​
    @CacheEvict(value = "user", allEntries = true) // 移除所有数据
    public void deleteAll() {
        log.info("delete All");
    }
​
}

集成EhCache

添加依赖

<dependency>  
    <groupId>net.sf.ehcache</groupId>  
    <artifactId>ehcache</artifactId>  
</dependency> 

ehcache.xml放到src/main/resources,配置spring.cache.ehcache.config: classpath:ehcache.xml

如果想自定义设置一些个性化参数时,通过Java Config形式配置。

@Configuration  
@EnableCaching  
public class CacheConfig {  
  
    @Bean  
    public CacheManager cacheManager() {  
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());  
    }  
  
    @Bean  
    public EhCacheManagerFactoryBean ehCacheCacheManager() {  
        EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();  
        cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));  
        cmfb.setShared(true);  
        return cmfb;  
    }  
  
}

缓存的对象必须实现Serializable

猜你喜欢

转载自blog.csdn.net/cowbin2012/article/details/85220033