spring cache快速入门

 以redis为例

使用方法:

  1. 导入maven坐标spring-boot-starter-cache和spring-boot-starter-data-redis
  2. 启动类上加注解@EnableCaching,开启缓存注解功能
  3. controller层引入注解

注意:如果想要把类加进缓存中,那么类应该实现序列化接口,比如user类

@Data
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private String name;
    private int age;
    private String address;
}

             

spring cache常用注解

@EnableCaching

开启缓存注解功能,和启动类一起用(@springbootapplication)

@CacheEvict

用于方法上,将一条或多条数据从缓存中删除。修改/删除mysql数据后,需删除缓存中对应数据

@CachePut

用于方法上,将方法返回值放到缓存中

@Cacheable

用于方法上,在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中

注解参数:

#id:获取方法的id参数

#result代指方法返回值,如这个例子,代指user

*condition意为条件。对入参进行判断,符合条件的缓存,不符合的不缓存。
* unless:意为除非。对出参进行判断,判断为true,不缓存。这里null为空,则不缓存

*key字符串拼接法:key = "#user.id + '_' + #user.name"

    @Cacheable(value = "userCache",key = "#id",unless = "#result == null")
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id){
        User user = userService.getById(id);
        return user;
    }

实例:

1、导入maven坐标

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

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

2、配置application.yml

server:
  port: 8080
spring:
  application:
    #应用的名称,可选
    name: cache_demo
  datasource:
    druid: #德鲁伊
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: root
      password: root
  redis: #配置redis参数
    host: 172.29.254.50 #reids ip4地址
    port: 6379 #端口号
    password: root@123456
    database: 0 #0号redis数据库
  cache: #设置spring cache参数   
    redis:
      time-to-live: 1800000 #设置spring cache缓存过期时间(单位毫秒,即1800秒,半小时),可选
mybatis-plus:
  configuration:
    #在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: ASSIGN_ID

3、开启缓存注解功能

@Slf4j
//启动类
@SpringBootApplication
//功能:Servlet(控制器)、Filter(过滤器)、Listener(监听器)可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册到Spring容器中,无需其他代码。
@ServletComponentScan
//开启事务控制
@EnableTransactionManagement
//开启缓存注解功能
@EnableCaching
public class CacheDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheDemoApplication.class,args);
        log.info("项目启动成功...");
    }
}

4、被缓存的类实现序列化接口

@Data
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private String name;
    private int age;
    private String address;
}

5、创建cache_demo数据库,并创造user表

6、创建mapper、service、controller层

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * CachePut:将方法返回值放入缓存
     * value:缓存的名称,每个缓存名称下面可以有多个key(redis'中的键名"userCache::5")
     * key:缓存的key
     */
    @CachePut(value = "userCache",key = "#user.id")
    @PostMapping
    public User save(User user){
        userService.save(user);
        return user;
    }

    /**
     * CacheEvict:清理指定缓存
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     */
    @CacheEvict(value = "userCache",key = "#id")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        userService.removeById(id);
    }
     //result:方法返回值,这这里代指user
    @CacheEvict(value = "userCache",key = "#result.id")
    @PutMapping
    public User update(User user){
        userService.updateById(user);
        return user;
    }

    /**
     * Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     * condition:意为条件。对入参进行判断,符合条件的缓存,不符合的不缓存。
     * unless:意为除非。对出参进行判断,判断为true,不缓存。这里null为空,则不缓存
* result:方法返回值,这里代指user
     */
    @Cacheable(value = "userCache",key = "#id",unless = "#result == null")
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id){
        User user = userService.getById(id);

        return user;
    }

    @Cacheable(value = "userCache",key = "#user.id + '_' + #user.name")
    @GetMapping("/list")
    public List<User> list(User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user.getId() != null,User::getId,user.getId());
        queryWrapper.eq(user.getName() != null,User::getName,user.getName());
        List<User> list = userService.list(queryWrapper);
        return list;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值