SpringBoot入门之SpringBoot整合Redis 08

8. SpringBoot整合Redis

8.1 pom文件引入redis启动器

注意:redis启动器一定要有版本号,没有版本号pom文件也不会报错,代码中也能加入相应注解,但是SpringBoot无法将数据存到redis中.切记切记一定要有版本号

 <!--Redis启动器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>1.2.8.RELEASE</version>
</dependency>

8.2 启动类加入@EnableCaching

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * 这是启动类
 */
@SpringBootApplication
@EnableCaching //开启redis缓存
public class SpringBootApplicationRunner {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplicationRunner.class,args);

    }
}

8.3 需求1: 查找所有用户时,就把数据存到redis中

  1. service.impl包下的UserServiceImpl类中的findAll()方法, 在此方法上加上@Cacheable注解, value="findAll"指的是存入redis中的key为findAll
 @Cacheable(value = "findAll")
    public List<User> findAll() {
        System.out.println("从数据库查询数据********************");
        return userDao.findAll();
    }
  1. 启动redis-server.exe
    在这里插入图片描述
    启动后的redis是这样滴~
    在这里插入图片描述
  2. 启动redis-client.exe, 用于查看redis中的数据
    在这里插入图片描述
  3. 启动项目,浏览器范围localhost:8080/user.html, 然后redis客户端界面输入keys *,会发现key=findAll已存入redis中.
    在这里插入图片描述

8.4 需求2: 删除redis中的数据

  1. service.impl包下的UserServiceImpl类中的**findUserByName()**方法, 在此方法上加上@CacheEvict注解, value="findAll"指的是删除redis中key为findAll的数据, allEntries = true代表确定要删除数据.
@Override
@CacheEvict(value = "findAll",allEntries = true)
public List<User> findUserByName(String name) {
    return userMapper.queryUserByName(name);
}
  1. 重启项目, 浏览器输入localhost:8080/user/findUserByName/张. 然后再在redis-client客户端输入keys *, 会发现没有数据了, 说明redis中的数据已被删除.
    在这里插入图片描述
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值