一.代码示例
1.pom配置坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
2.application配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
mybatis-plus:
global-config:
db-config:
table-prefix: learning_
id-type: auto
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.启用缓存
package com.learning;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
/**
* @Author wangyouhui
* @Description TODO
**/
@SpringBootApplication
// 开启缓存
@EnableCaching
public class SpringBootLearningApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootLearningApplication.class, args);
}
}
4.controller
package com.learning.controller;
import com.learning.domain.Student;
import com.learning.service.StudentService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author wangyouhui
* @Description 测试缓存
**/
@RestController
@RequestMapping("/cache")
@AllArgsConstructor
public class CacheController {
private StudentService studentService;
@GetMapping("/get")
public Student get(String id){
return studentService.getById(id);
}
}
5.service
1.@Cacheable既会存,也会取
2.@CachePut只会存,不会取
package com.learning.service.impl;
import com.learning.dao.StudentDao;
import com.learning.domain.Student;
import com.learning.service.StudentService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* @Author wangyouhui
* @Description 学生实现类
**/
@Service
@AllArgsConstructor
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao;
@Override
@Cacheable(value="studentCache", key="#id")
public Student getById(String id) {
return studentDao.selectById(id);
}
}
6.dao
package com.learning.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.learning.domain.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentDao extends BaseMapper<Student> {
}
二.效果示例
1. 查询两次接口,只会查询一次日志
2.数据库截图
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/92343.html