728x90
외부 라이브러리
Memory라는 외부 라이브러리라고 생각하고 만들어 보자(패키지도 분리했다)
Memory
public class Memory {
private long used;
private long max;
public Memory(long used, long max) {
this.used = used;
this.max = max;
}
public long getMax() {
return max;
}
public long getUsed() {
return used;
}
@Override
public String toString() {
return "Memory{" +
"used=" + used +
", max=" + max +
'}';
}
}
- used : 사용중인 메모리
- max : 최대 메모리
- 쉽게 이야기해서 used 가 max 를 넘게 되면 메모리 부족 오류가 발생한다
MemoryFinder
@Slf4j
public class MemoryFinder {
public Memory get(){
long max = Runtime.getRuntime().maxMemory();
long total = Runtime.getRuntime().totalMemory();
long free = Runtime.getRuntime().freeMemory();
long used = total - free;
return new Memory(used, max);
}
@PostConstruct
public void init(){
log.info("init memoryFinder");
}
}
- JVM에서 메모리 정보를 실시간으로 조회하는 기능이다.
- max 는 JVM이 사용할 수 있는 최대 메모리, 이 수치를 넘어가면 OOM이 발생한다.
- total 은 JVM이 확보한 전체 메모리(JVM은 처음부터 max 까지 다 확보하지 않고 필요할 때 마다 조금씩 확보한다.)
- free 는 total 중에 사용하지 않은 메모리(JVM이 확보한 전체 메모리 중에 사용하지 않은 것)
- used 는 JVM이 사용중인 메모리이다.( used = total - free )
MemoryController
@Slf4j
@RestController
@RequiredArgsConstructor
public class MemoryController {
private final MemoryFinder memoryFinder;
@GetMapping("/memory")
public Memory system(){
Memory memory = memoryFinder.get();
log.info("memory={}", memory);
return memory;
}
}
- 메모리 정보를 조회하는 컨트롤러이다.
- 앞서 만든 memoryFinder 를 주입 받아 사용한다.
내 프로젝트
MemoryConfig
@Configuration
public class MemoryConfig {
@Bean
public MemoryFinder memoryFinder(){
return new MemoryFinder();
}
@Bean
public MemoryController memoryController(){
return new MemoryController(memoryFinder());
}
}
- memoryController , memoryFinder 를 빈으로 등록하자.
- 패키지 위치에 주의하자 hello.config 에 위치한다
-
패키지를 이렇게 나눈 이유는, memory라는 완전히 별도의 모듈이 있고, hello 에서 memory의 기능을 불러다 사용한다고 이해하면 된다.
-
728x90
'스프링 부트(핵심 원리와 활용)' 카테고리의 다른 글
| Ch04. 자동 구성(Auto Configuration) - 순수 라이브러리 만들기 (0) | 2023.03.10 |
|---|---|
| Ch04. 자동 구성(Auto Configuration) - @Conditional (0) | 2023.03.09 |
| Ch04. 자동 구성(Auto Configuration) - 스프링 부트의 자동 구성 (0) | 2023.03.09 |
| Ch04. 자동 구성(Auto Configuration) - 자동 구성 확인 (0) | 2023.03.09 |
| Ch04. 자동 구성(Auto Configuration) - 예제 만들기 (0) | 2023.03.08 |