1. 创建一个 demo 项目
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.5.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <groupId>com.example</groupId>
- <artifactId>demo</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>demo</name>
- <description>Demo project for Spring Boot</description>
- <properties>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </project>
2. 配置 DemoApplication 文件
- @SpringBootApplication
- @EnableCaching
- public class DemoApplication {
- public static void main(String[] args) {
- SpringApplication.run(DemoApplication.class, args);
- }
- }
3. 编写 DemoController
- @RestController
- public class DemoController {
- @Autowired
- private DemoService demoService;
- @GetMapping("demo")
- public boolean demo(@RequestParam("id") Integer id){
- return demoService.demo(id);
- }
- }
4. 编写 DemoService
- package com.example.demo;
- import org.springframework.cache.annotation.Cacheable;
- import org.springframework.stereotype.Service;
- @Service
- public class DemoService {
- /**
- * 当 id 大于 10 时使用缓存
- * 当 id 小于或等于 10 时不使用缓存
- * @param id
- * @return
- */
- @Cacheable(value = "id",key = "#id",condition = "#id>10")
- public boolean demo(Integer id){
- System.out.println("----> 未使用缓存");
- if(id==20){
- return true;
- }else{
- return false;
- }
- }
- }
5. 配置服务端口
server.port=1111
6. 测试
http://127.0.0.1:1111/demo?id=10
7.spring-boot 使用 tools-Redis 实现分布式缓存
来源: https://yq.aliyun.com/articles/706690