springboot2.x整合redis注解@Cacheable\@CachePut\@CacheEvict

springboot整合redis实际开发中常用到的几个注解

一、准备 

1、pom文件引入redis 缓存

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

2、程序入口类上加上注解 @EnableCaching

3、配置数据源(mysql)

spring:
  # redis
  redis:
    host: 49.235.114.xx
    port: 6379
    database: 1
    password: xxxx
    # mysql
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/xxx?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8
    username: root
    password: xxxx

二、redis注解使用的SpEL表达式

1、#root.methodName:当前被调用的方法名

2、#root.method.name:当前被调用的方法

3、#root.target:当前被调用的目标对象

4、#root.targetClass:当前被调用的目标对象类

5、#root.arg[0]:当前被调用方法的参数列表

6、#a0#p0 :方法参数名字,0表示参数的索引

7、#result :方法执行后的返回值

三、注解

1、@Cacheable

1)cacheNames / value:指定缓存组键的名字

(例如员工的,还是客户的),可指定多个缓存(数组)

2)key:缓存数据时用的key

 默认使用方法参数的值

3)condition:指定符合条件的情况下才缓存

4)unless:否定缓存;

当unless指定的条件为true,方法的返回值就不会缓存;可以获取结果进行判断  

5) sync : 缓存是否使用异步

例子1:

@Cacheable(cacheNames = {"user"},key="#root.methodName+'['+#loginName+']'"unless="#result==null")
    public User selectUserByLoginName(String loginName){...}

2、@CachePut

先调用方法,后更新缓存数据,用于修改了数据库某个数据,同时更新缓存使用 

与@Cacheable不同,@Cacheable先查询缓存,有则直接返回,没有则走方法。

@CachePut(value = {"users"},key="#user.loginName",unless = "#result==null")
public User updateUser(User user) {
    if(userMapper.updateById(user)==1) {
        return user;
    }else {
        return null;
    }
};

//记住返回值也要是User实体类

3、@CacheEvict

allEntries=true:指定清除这个缓存中所有的数据

beforeInvocation=false:缓存的清除是否在方法之前执行(默认在方法执行后执行)

@CacheEvict(value="user",key="#user.loginName",beforeInvocation=false)

public Boolean deleteById(User user)

{
     return this.removeById(user);
 }

 

4、@CacheConfig

这个注解是写在类上的,如果在userService中,每次都要写value="user"或者cacheNames = "user",就会显得注解很长,可以在类上写上注解

@CacheConfig(cacheNames="user")

class userServiceImpl{...}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百里东君~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值