Spring boot

[Spring Boot] JPA Caching 적용하기

민뭉아치 2022. 3. 21. 19:21

Dependency

implementation group: 'org.springframework.boot', name: 'spring-boot-starter-cache'
  • ConcurrentHashMap
  • caffeine

application.yml

logging:
	level:
		org:
			hibernate:
				SQL:DEBUG
				type.descriptor.sql.BasicBinder:DEBUG

mainApplication.java

@SpringBootApplication
@EnableCaching
public class mainApplication {
    public static void main(String[] args) {
        SpringApplication.run(mainApplication.class, args);
    }

}

@EnableCache

Entity

@Data
@Entity
public class User {
	@Id
	private long id;
	private String name;
	private String password;
}

Service

@Service
public class UserService {
	private UserRepository userRepository;

	public HelloService(@Autowired UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	@Cacheable("getUserAll")
	public List<User> getUserAll() {
		List<User> user = this.userRepository.findAll();
		return user;
	}

}

@Cacheable : 자주 쓰이는 함수에 붙이면 된다. 이름을 설정해야한다.,

Repository

public interface UserRepository implements Crud... {
}

Test

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloServiceTest {
	@Autowired
	private UserService userService;

	@Autowired
	private UserRepository userRepository;

	@Test
	public void getUserAll() {
		User user = new User();
		user.setId(1);
		user.setName("test");
		user.setPassword("testpwd");
		userRepository.save(user);

		List<User> users = userService.getUserAll();
		assertEquals(1, users.size());

		Sysyem.out.pringln(userService.getUserAll());
		Sysyem.out.pringln(userService.getUserAll());
		Sysyem.out.pringln(userService.getUserAll());
	}

}

여러번 getUserAll() 메서드를 호출해본 결과 쿼리문은 따로 실행되지 않음을 확인할 수 있다.

 

캐싱 적용 확인

  • h2 Query를 보여주는 show-sql 속성을 true로 설정하여 판단한다.
spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:testdb
    username: sa
    password:
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.H2Dialect

 

참고 영상