`
rensanning
  • 浏览: 3509801 次
  • 性别: Icon_minigender_1
  • 来自: 大连
博客专栏
Efef1dba-f7dd-3931-8a61-8e1c76c3e39f
使用Titanium Mo...
浏览量:37406
Bbab2146-6e1d-3c50-acd6-c8bae29e307d
Cordova 3.x入门...
浏览量:603971
C08766e7-8a33-3f9b-9155-654af05c3484
常用Java开源Libra...
浏览量:677508
77063fb3-0ee7-3bfa-9c72-2a0234ebf83e
搭建 CentOS 6 服...
浏览量:86987
E40e5e76-1f3b-398e-b6a6-dc9cfbb38156
Spring Boot 入...
浏览量:399566
Abe39461-b089-344f-99fa-cdfbddea0e18
基于Spring Secu...
浏览量:68982
66a41a70-fdf0-3dc9-aa31-19b7e8b24672
MQTT入门
浏览量:90293
社区版块
存档分类
最新评论

Spring Boot 入门 - 进阶篇(5)- 数据缓存(@Cacheable)

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

(1)添加 spring-boot-starter-cache 依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>


(2)开启缓存功能
@Configuration
@EnableCaching
public class CacheConfig {

}


(3)缓存数据
对于缓存的操作,主要有:@Cacheable、@CachePut、@CacheEvict。

@Cacheable
Spring 在执行 @Cacheable 标注的方法前先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,执行该方法并将方法返回值放进缓存。
参数: value缓存名、 key缓存键值、 condition满足缓存条件、unless否决缓存条件
@Cacheable(value = "user", key = "#id")
public User findById(final Long id) {
    System.out.println("cache miss, invoke find by id, id:" + id);
    for (User user : users) {
        if (user.getId().equals(id)) {
            return user;
        }
    }
    return null;
}


@CachePut
和 @Cacheable 类似,但会把方法的返回值放入缓存中, 主要用于数据新增和修改方法。
@CachePut(value = "user", key = "#user.id")
public User save(User user) {
    users.add(user);
    return user;
}


@CacheEvict
方法执行成功后会从缓存中移除相应数据。
参数: value缓存名、 key缓存键值、 condition满足缓存条件、 unless否决缓存条件、 allEntries是否移除所有数据(设置为true时会移除所有缓存)
@CacheEvict(value = "user", key = "#user.id") // 移除指定key的数据
public User delete(User user) {
    users.remove(user);
    return user;
}

@CacheEvict(value = "user", allEntries = true) // 移除所有数据
public void deleteAll() {
    users.clear();
}


(4)集成EhCache

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


SpringBoot可以自动配置不需要什么特殊设置即可使用。

src/main/resources/ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <cache name="user" maxEntriesLocalHeap="200" timeToLiveSeconds="600">
    </cache>
</ehcache>


src\main\resources/application.properties
引用
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;
	}

}


(5)组合CacheManager

从多个CacheManager中轮询得到相应的Cache。

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager compositeCacheManager(RedisTemplate<Object, Object> redisTemplate) {
        CompositeCacheManager cacheManager = new CompositeCacheManager(new ConcurrentMapCacheManager(), new SimpleCacheManager());
        cacheManager.setFallbackToNoOpCache(false);
        cacheManager.afterPropertiesSet();
        return cacheManager;
    }

}


*** 设置缓存无效化 spring.cache.type=none
*** 缓存的对象必须实现Serializable
*** 除GuavaCacheManager之外都支持Spring事务,即回滚时Cache的数据也会被移除
分享到:
评论

相关推荐

    尚硅谷Java视频教程_Spring Boot视频教程(下)整合篇

    5、尚硅谷-SpringBoot高级-缓存-缓存工作原理&@Cacheable运行流程 6、尚硅谷-SpringBoot高级-缓存-@Cacheable其他属性 7、尚硅谷-SpringBoot高级-缓存-@CachePut 8、尚硅谷-SpringBoot高级-缓存-@CacheEvict 9、...

    128元尚硅谷Java视频教程_Spring Boot视频教程(下)整合篇

    5、尚硅谷-SpringBoot高级-缓存-缓存工作原理&@Cacheable运行流程 6、尚硅谷-SpringBoot高级-缓存-@Cacheable其他属性 7、尚硅谷-SpringBoot高级-缓存-@CachePut 8、尚硅谷-SpringBoot高级-缓存-@CacheEvict 9、...

    Java课程实验 Spring Boot 缓存管理

    在Spring Boot中,你可以使用Spring框架提供的缓存管理来提高应用程序的性能。Spring Boot支持多种缓存实现,包括内存缓存和分布式缓存。 1.添加缓存依赖: 在项目的 pom.xml 文件中添加所需的缓存依赖。 2.配置缓存...

    3.1、spring boot redis注解缓存Cacheable (value) 1

    3.1、spring boot redis注解缓存Cacheable (value) 1

    SpringBoot笔记-下篇.pdf

    一、Spring Boot与缓存 一、JSR107 Java Caching定义了5个核心接口,分别是CachingProvider, CacheManager, Cache, Entry 和 Expiry。 • CachingProvider定义了创建、配置、获取、管理和控制多个CacheManager。一个...

    springboot 整合ehcache+redis 通过配置文件切换缓存类型

    ehcache :添加依赖 pom.xml 2、添加配置文件ehcache.xml 3、添加注解@EnableCaching @Cacheable 4、插入缓存 5 读取缓存 6 设置缓存过期时间ehcache.xml --&gt;timeToLiveSeconds。 redis : 1、添加依赖 pom.xml 2、...

    SpringBoot常用注解详解含使用示例(值得珍藏)

    本文将详细介绍Spring Boot中最常用的注解,包括@SpringBootApplication、@Component、@Service、@Repository、@Controller、@RequestMapping、@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@Autowired...

    Spring Cache的基本使用与实现原理详解

    缓存是实际工作中非经常常使用的一种提高性能的方法, 我们会在很多场景下来...下面这篇文章主要给大家介绍了关于Spring Cache的基本使用与实现原理的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下

    springboot整合ehcache 设置缓存过期时间 简单示例

    springboot 整合 ehcache 简单示例 1、添加依赖 pom.xml 2、添加配置文件ehcache.xml 3、添加注解@EnableCaching @Cacheable 4、插入缓存 5 读取缓存 6 设置缓存过期时间ehcache.xml --&gt;timeToLiveSeconds。

    springboot 整合 redis 简单示例 (可设置缓存过期)

    springboot 整合 redis 简单示例 1、添加依赖 pom.xml 2、主入口添加注解@EnableCaching 获取缓存方法添加@Cacheable 3、初始化缓存管理器 4 实现put get方法 其中一个put方法添加了过期时间 5 调用方法获取缓存。...

    代码生成器-可自定义模版-guns

    系统地讲解了如何构建一个日常生产环境实用的基于Spring Boot并且集成springmvc + shiro + mybatis-plus + beetl的后台管理系统,可管理代码生成模版,管理连接生成代码的数据库. Guns框架自带的功能:1.用户管理 2....

    SpringBoot高级1

    1 . @Cacheable/@CachePut/@CacheEvict 主要的参数 2 . 缓存可用的SpEL表达式 1. 基本使用步骤 1. 引入sprin

Global site tag (gtag.js) - Google Analytics