Spring Cache 使用

结合MyBatis一起使用,MyBatis相关的内容省略

@Cacheable支持如下参数:根据方法的请求参数对其结果进行缓存
value:缓存位置名称,不能为空.
key:缓存的key,默认为空,支持springEL表达式,如果为空缺省按照方法的所有参数进行组合
condition:触发条件,只有满足条件的情况下才会加入缓存,默认为空,表示全部加入缓存,支持springEL表达式.

@CachEvict支持如下参数:负责清除缓存.
value:缓存位置名称,不能为空.
key:缓存的key,默认为空,支持springEL表达式.
condition:触发条件,只有满足条件的情况下才会清除缓存,默认为空,支持springEL表达式.
allEntries:ture表示清除value中的全部缓存,默认为false.
beforeInvocation:是否在方法执行前就清空,缺省为false,如果指定为 true则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存

@CachePut作用和配置方法
根据方法的请求参数对其结果进行缓存,和@Cacheable不同的是,它每次都会触发真实方法的调用.
value:缓存位置名称,不能为空.
key:缓存的key,可以为空,支持使用SpEL编写,如果为空缺省按照方法的所有参数进行组合.
condition:缓存的条件,可以为空,支持使用SpEL编写,如果为空缓存全部数据.

1.service

@Service("userService")
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @CacheEvict(value="userCache",allEntries=true)
    public int deleteByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    };

    @CacheEvict(value="userCache",allEntries=true)
    public User insert(User user) {
        //ID自动新增,新增保存时获取新增记录的ID
        userMapper.insert(user);
        return user;
    };

    @Cacheable(value="userCache")
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    };

    @Cacheable(value="userCache")
    public List<User> selectAll() {
        return userMapper.selectAll();
    };

    @CacheEvict(value="userCache",allEntries=true)
    public int updateByPrimaryKey(User user) {
        return userMapper.updateByPrimaryKey(user);
    };
}

2.applicationContext.xml中关于Cache的配置
引入xmlns:cache=”http://www.springframework.org/schema/cache”

    <!-- 应用spring cache注解功能  -->  
    <cache:annotation-driven />  

    <!-- 创建spring cache bean -->  
    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">  
        <property name="caches">  
            <set>  
                <bean  
                    class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"  
                    p:name="default" />  
                <bean  
                    class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"  
                    p:name="userCache" />  
            </set>  
        </property>  
    </bean>  

3.测试

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = applicationContext.getBean("userService",UserService.class);
        User user = userService.selectByPrimaryKey(4);//第一次查询,从数据库获取
        System.out.println(user);
        user = userService.selectByPrimaryKey(4);//第二次查询,从缓存中获取
        System.out.println(user);
        user = new User();
        user.setName("张三");
        user = userService.insert(user);//新增记录,清空所有缓存
        System.out.println(user);

        user = userService.selectByPrimaryKey(4);//第三次查询,从数据库获取
        System.out.println(user);

4.按指定key从缓存中移除

@Service("userService")
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @CacheEvict(value="userCache",key="#id")
    public int deleteByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    };

    @CacheEvict(value="userCache",key="#user.id")
    public User insert(User user) {
        //ID自动新增,新增保存时获取新增记录的ID
        userMapper.insert(user);
        return user;
    };

    @Cacheable(value="userCache")
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    };

    @Cacheable(value="userCache")
    public List<User> selectAll() {
        return userMapper.selectAll();
    };

    @CacheEvict(value="userCache",key="#user.id")
    public int updateByPrimaryKey(User user) {
        return userMapper.updateByPrimaryKey(user);
    };
}

5.测试

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = applicationContext.getBean("userService",UserService.class);
        User user = userService.selectByPrimaryKey(4);//第一次查询,从数据库获取
        System.out.println(user);
        user = userService.selectByPrimaryKey(4);//第二次查询,从缓存中获取
        System.out.println(user);
        user = new User();
        user.setName("张三");
        user = userService.insert(user);//新增记录,清空指定缓存
        System.out.println(user);

        user = userService.selectByPrimaryKey(4);//第三次查询,从缓存获取
        System.out.println(user);

参考:
Spring Cache使用 http://liuxing.info/2015/06/18/Spring%20Cache%E4%BD%BF%E7%94%A8/
注释驱动的 Spring cache 缓存介绍 https://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/
Spring使用Cache、整合Ehcache http://www.mincoder.com/article/2096.shtml

Spring CacheSpring框架提供的一种缓存机制,用于提高应用程序的性能和响应速度。通过使用Spring Cache,可以将方法的返回值缓存起来,当下次调用相同的方法时,可以直接从缓存中获取结果,而不需要再执行方法的逻辑。 在使用Spring Cache时,需要进行一些配置。首先,需要添加Redis的配置信息,包括缓存类型、缓存过期时间、缓存键的前缀等。可以通过设置`spring.cache.type`为`redis`来指定使用Redis作为缓存类型。可以使用`spring.cache.redis.time-to-live`设置缓存的过期时间,单位为毫秒。可以使用`spring.cache.redis.key-prefix`设置缓存键的前缀,如果不指定前缀,则默认使用缓存的名字作为前缀。可以使用`spring.cache.redis.use-key-prefix`设置是否使用前缀,默认为true。可以使用`spring.cache.redis.cache-null-values`设置是否缓存空值,以防止缓存穿透。 另外,Spring Cache还支持使用JCache(JSR-107)注解来简化开发。从Spring 3.1开始,定义了`org.springframework.cache.Cache`和`org.springframework.cache.CacheManager`接口来统一不同的缓存技术。 在使用Spring Cache时,可以通过在方法上添加`@Cacheable`注解来启用缓存功能。当调用带有`@Cacheable`注解的方法时,Spring会首先检查缓存中是否存在相应的结果,如果存在,则直接返回缓存中的结果,如果不存在,则执行方法的逻辑,并将结果存入缓存中。 总结起来,使用Spring Cache可以通过配置Redis等缓存信息,并在方法上添加`@Cacheable`注解来实现缓存功能,提高应用程序的性能和响应速度。 #### 引用[.reference_title] - *1* [SpringCache使用](https://blog.csdn.net/ABestRookie/article/details/121297482)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [springcache使用详解(使用redis做分布式缓存)](https://blog.csdn.net/A_art_xiang/article/details/125580962)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值