> For the complete documentation index, see [llms.txt](https://blakes-organization.gitbook.io/rainsister/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://blakes-organization.gitbook.io/rainsister/springboot-2.x/up-cache/thread-cache.md).

# Thread내캐쉬사용 및 Cache 어노테이션 사용법

이전에 작성된 글을 먼저 읽어 보자 [Broken mention](broken://pages/BSrgUI2z1fjUryKByy9Y). 여기서 작성 되었던 아래 코드를 보자

```java
@Entity
@Data
@NoArgsConstructor
public class User {

    @Id
    @GeneratedValue
    private Long id;

    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}
```

User 객체

```java
public interface UserRepository extends JpaRepository<User, Long> {

    User findByName(String name);

    User findByNameAndAge(String name, Integer age);

    @Query("from User u where u.name=:name")
    User findUser(@Param("name") String name);

}

```

application.properties 또는 application.yml 파일에 아래와 같은 속성을 추가한다.

```properties
spring.jpa.show-sql=true
## springboot 1.x 는 아래 설정 사용
spring.jpa.properties.hibernate.show_sql=true

```

application.yml

```yaml
spring:
    jpa:
        show-sql: true
        # springboot 1.x 는 아래 설정 사용
        properties:
            hibernate:
                show_sql: true
        
```

테스트 코드 작성

```java
@RunWith(SpringRunner.class)
@SpringBootTest
public class CacheDemoApplicationTests {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() throws Exception {

        userRepository.save(new User("AAA", 10));

        User u1 = userRepository.findByName("AAA");
        System.out.println("첫번째 조회 : " + u1.getAge());

        User u2 = userRepository.findByName("AAA");
        System.out.println("두번째 조회 ：" + u2.getAge());
    }

}
```

아직 cache 설정을 적용하지 않았으니 당연히 2번 수행 로그는 동일하다. 즉 findByName 를 두번 실해안 쿼리는 동일하다.

```
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
첫번째 조회 : 10
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
두번째 조회 : 10
```

### Cache 설정 시작

pom.xml

```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
```

main class 에서 cache 활성화 어노테이션 @EnableCaching  를 적용한다. 아래 코드 참조

```java
@EnableCaching
@SpringBootApplication
public class CacheDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(Chapter51Application.class, args);
	}

}
```

Interface 에도 오노테이션 적용 @CacheConfig(cacheNames = "users")

```java
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {

    @Cacheable
    User findByName(String name);

}
```

아까 테스트 코드를 다시 수행해본다.

```
Hibernate: insert into user (age, name, id) values (?, ?, ?)
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
첫번째 조회 : 10
두번째 조회 : 10
```

로그에 찍힌것 처럼 findByName 수행에서 첫번째 조회 시 쿼리가 나갔지만 두번째 조회는 안니다.&#x20;

좀 더 확인해보고 싶으면??? CacheManager 를 주입받으면 된다.

<pre class="language-java"><code class="lang-java"><strong>@RunWith(SpringRunner.class)
</strong>@SpringBootTest
public class CacheDemoApplicationTests {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CacheManager cacheManager;   //CacheManager 주입받는다.
    @Test
    public void test() throws Exception {

</code></pre>

디버깅 해보면&#x20;

<figure><img src="/files/gIntWPYtVWY92jWGNC2t" alt=""><figcaption></figcaption></figure>
