# Redis를 사용하여 Cache 관리하기

EhCache 는 thread 내의 cache 전용이여서 분산시스템환경에서 사용하기에는 적합하지 않다. 물론 EhCache 자체도 분산시스템을 지원하지만 캐쉬가 동기화 되지 않는 경우 많다.&#x20;

아래에 Srpingboot 내부에서 지원한 redis cache 를 설정하고 사용해보자.

동일하게 지난번 사례 코드를 그대로 적용해보자

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

    @Id
    @GeneratedValue
    private Long id;

    private String name;
    private Integer age;

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

interface 더 만든다.

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

    @Cacheable
    User findByName(String name);

}

```

pom.xml 에 dependency를 추가한다.

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

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
```

{% hint style="info" %}
주의! springboot 1.x 에서 명칭은 spring-boot-starter-redis 로 되어 있다. 잘 구분 하자!
{% endhint %}

application.properties

```properties
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=100ms
```

application.yml

```yaml
spring:
    redis:
        host: localhost
        lettuce:
            pool:
                max-active: 8
                max-idle: 8
                max-wait: -1ms
                min-idle: 0
            shutdown-timeout: 100ms
        port: 6379
```

{% hint style="info" %}
Redis conncetion pool 설정 관련 하여 주의해야 될 부분은 springboot1.x 에서  spring.redis.pool 를 사용한다.

1.x 에서는 jedis 를 사용하고

2.x 에서는 lettuce 를 사용한다.
{% endhint %}

테스트 코드를 작성

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

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CacheManager cacheManager;

    @Test
    public void test() throws Exception {
        System.out.println("CacheManager type : " + cacheManager.getClass());

        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());
    }

}
```

```
CacheManager type : class org.springframework.data.redis.cache.RedisCacheManager
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into user (age, name, id) values (?, ?, ?)
2020-08-12 16:25:26.954  INFO 68282 --- [           main] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2020-08-12 16:25:26.955  INFO 68282 --- [           main] io.lettuce.core.KqueueProvider           : Starting without optional kqueue library
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
```

로그에서 찍힌 대로 &#x20;

* CacheManager type : class org.springframework.data.redis.cache.RedisCacheManager&#x20;
* 두번째 조회시 SQL 이 수행되지 않았다.

끝!&#x20;


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blakes-organization.gitbook.io/rainsister/springboot-2.x/up-cache/redis-cache.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
