需要把mysql数据在Redis缓存中进行备份

引入pom.xml文件:

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

application.yml文件中加上:

 jpa:
    database: mysql
    show-sql: true #显示sql语句
    generate-ddl: true #可以自动创建表
     #报错:Error executing DDL,解决方案:设置数据库引擎为InnoDB
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
redis:
    host: 192.168.48.5
    port: 6379

这里用的是jpa实现的所有需要加上jpa的相关的配置。
ServiceImpl层:

    @Autowired

    private RedisTemplate redisTemplate;
    @Override
    public List<Student> queryAllStudents() {
//从缓存里面查询
//写法一
        List<Student> stus =(List<Student>) redisTemplate.boundValueOps("stu").get();
//       写法二
//        List<Student> stus1 = (List<Student>)redisTemplate.opsForValue().get("stus");


//        Object stus1 = redisTemplate.opsForValue().get("stus");
        if(stus==null){
            stus=studentDao.findAll();
            System.out.println("mysql");
//            没有把数据同时存储到缓存里面
//  写法一
        redisTemplate.boundValueOps("stus").set(stus);

//        写法二
//            redisTemplate.opsForValue().set("stus",stus);
}


        return stus;
    }

controller层进行相关的测试:

@RestController
@RequestMapping("stu")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping
    public List<Student> students(){

        return studentService.queryAllStudents();
    }
}
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐