봄 캐시 API
캐시 1. 유형
1.1 메모리 캐싱 如의 레디 스.
1.2 데이터베이스 캐싱 如 최대 절전 캐시.
2. 봄 부팅 캐시 주석
프로젝트 초기화 https://start.spring.io/을
2.1 만들기 HTTP GET REST API
Student.java
패키지 com.example.springcache.domain;
공용 클래스 학생 {
문자열 ID;
문자열 이름;
문자열 CLZ;
공공 학생 (문자열 ID, 문자열 이름, 문자열 CLZ) {
슈퍼 ();
this.id = ID;
this.name = 이름;
this.clz = CLZ;
}
// 세터와 게터 //注意把설정和GET方法加上
}
StudentService.java
package com.example.springcache.service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.example.springcache.domain.Student;
@Service
public class StudentService
{
@Cacheable("student")
public Student getStudentByID(String id)
{
try
{
System.out.println("Going to sleep for 5 Secs.. to simulate backend call.");
Thread.sleep(1000*5);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return new Student(id,"Sajal" ,"V");
}
}
StudentController.java
package com.example.springcache.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.example.springcache.domain.Student; import com.example.springcache.service.StudentService; @RestController public class StudentController { @Autowired StudentService studentService; @GetMapping("/student/{id}") public Student findStudentById(@PathVariable String id) { System.out.println("Searching by ID : " + id); return studentService.getStudentByID(id); } }
Note:
- service层方法用
@Cacheable("student")
,用于cache学生信息。
2.2 Enable Spring managed Caching
SpringCacheApplication.java
package com.example.springcache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class SpringCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCacheApplication.class, args);
}
}
2.3 Demo test
http://localhost:8080/student/1
通过变换id,http://localhost:8080/student/2
感受一下缓存的效果。