springboot中使用缓存

个人博客地址:http://alexaccele.github.io/

1.导入cache模块

要在springboot中使用缓存技术首先要导入springboot的缓存模块,在pom文件中添加如下代码,或者在创建工程时选中cache模块,两者是一样的,选中cache模块也会在pom文件中添加如下代码

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

2.@EnableCaching开启基于注解的缓存

在配置类中添加@EnableCaching注解,也可以在程序主函数入口上标注

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class SpringbootConfiger {
}
@SpringBootApplication
@EnableCaching
public class Application {

    public static void main(String[] args) {
        Application.run(Application.class, args);
    }
}

3.在方法上标注缓存注解

   四个注解来声明缓存规则

注解描述
@Cacheable表明在调用方法之前,首先应该在缓存中查找方法的返回值。如果这个值能够找到,就会返回缓存的值。否则的话,这个方法就会被调用,返回值会放到缓存中
@CachePut表明应该将方法的返回值放到缓存中,在方法的调用前并不会检查缓存,方法始终都会调用
@CacheEvict表明应该在缓存中清除一个或多个条目,通常用于对数据库数据的删除方法,根据入参删除缓存中的内容。
@Caching这是一个分组的注解,能够同时应用多个其他的缓存注解

使用例子如下:

/*该方法会在缓存中先查找key为id的数据,如果存在则不会发送查询语句直接得到对象,否则执行方法进行查询并且返回的User对象会放入缓存中*/
@Cacheable
public User findOne(Long id){
    return repository.findOne(id);
}

/*无论缓存中是否存在key为id的User对象,都会执行方法进行查询并保存在缓存中*/
@CachePut
public User findOne(Long id){
    return repository.findOne(id);
}

/*不仅会删除数据库中id为User的数据,同时会清除缓存中id为User的数据*/
@CacheEvict
public User remove(Long id){
    return repository.remove(id);
}


/*@Cacheable和@CachePut注解的组合*/
@Caching(
    cacheable = {@Cacheable(value="user",key="#id")},
    put = {@CachePut(value="user",key="#result.name")}
)
public User findOne(Long id){
    return repository.findOne(id);
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值