rainsister
  • 신비한 비 Blog
  • Design Pattern
    • Adapter Pattern
    • Proxy Pattern
    • Mediator Pattern
    • Visitor Pattern
    • State Pattern
    • Memento Pattern
    • Factory Pattern
    • Template Pattern
    • Strategy Pattern
    • Bridge Pattern
  • springboot 2.x
    • 메시징 - 큐
      • RabbitMQ 기본설정
      • RabbitMQ 지연 큐(delayed queue)
    • Log
      • 기본 Log 설정 및 Logback 설정
      • Log4j2 사용해보기
      • tinylog 모듈 사용해보기
    • 기타 Database 에 대한 기본가이드
      • PostgreSQL
      • InfluxDB
      • MongoDB
    • 수행속도 UP! 각종 cache 어노테이션 사용법
      • Redis를 사용하여 Cache 관리하기
      • EhCache 사용해보기
      • Thread내캐쉬사용 및 Cache 어노테이션 사용법
    • Database Connection
      • Springboot 2.5 이후 data init script 초기화에 대한 변경
      • JTA 로 JPA 다중 DataSource 트랜잭션 처리 하기
      • Flyway 로 DataBase 형상 관리해보자
      • 트랜잭션 기초읽기
      • MyBatis 의 다중 DataSource
      • Spring Data JPA 다중 DataSource
      • JdbcTemplate 다중 DataSource
      • XML 로 Mybatis 설정하기
      • Mybatis 로 Mysql 연결하기
      • ORM(Spring data jpa)
      • Druid datasource 연결
      • Hikari 설정
      • JdbcTemplate 로 db 접근
    • rest api
      • XML에 대한 요청 및 응답 처리
      • SpringFox 3 및 Swagger 설정
      • 프로젝트 구동 시 RequestMappingHandler 로그 설정
      • Swagger 의 api들을 분류하는 법
      • 간단한 Restful API 만들고 테스트 코드 작성
      • Swagger2 구성하여 API 문서 자동화하기
      • JSR-303 그리고 validation
    • 설정
      • 시작
      • 멀티환경구성에 대한 새로운 방법
      • 멀티환경구성에 대한 새로운 include
      • 프로젝트 설정파일
      • 민감한 정보에 대한 암호화
  • java버전별차이
    • JAVA18
    • JAVA9
    • JAVA10
    • JAVA11
    • JAVA14
    • JAVA15
    • JAVA17
    • JAVA16
  • spring노하우
    • BeanUtils 권장하지 않는이유
    • 개인정보 암호화
    • Springboot 3가지 CROS 설정
    • Springboot 내장된 유용한 Utils
    • Spring Security WebSecurityConfigurerAdapter 가 deprecated 된 이슈해결하기
    • 아직도 HttpUtil ? SpringBoot 3.0의 HTTP Client Util 을 사용해보라
    • JDBC 소스를 뽀개기
    • spring-boot-configuration-processor 는 뭐하는놈임?
    • Apache BeanUtils vs Spring BeanUtils 성능비교
  • Effetive Java 3th
    • Finalizer & Cleaner
Powered by GitBook
On this page
  1. springboot 2.x
  2. 수행속도 UP! 각종 cache 어노테이션 사용법

Redis를 사용하여 Cache 관리하기

Redis and cache

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

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

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

@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 더 만든다.

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

    @Cacheable
    User findByName(String name);

}

pom.xml 에 dependency를 추가한다.

<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>

주의! springboot 1.x 에서 명칭은 spring-boot-starter-redis 로 되어 있다. 잘 구분 하자!

application.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

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

Redis conncetion pool 설정 관련 하여 주의해야 될 부분은 springboot1.x 에서 spring.redis.pool 를 사용한다.

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

2.x 에서는 lettuce 를 사용한다.

테스트 코드를 작성

@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

로그에서 찍힌 대로

  • CacheManager type : class org.springframework.data.redis.cache.RedisCacheManager

  • 두번째 조회시 SQL 이 수행되지 않았다.

끝!

Previous수행속도 UP! 각종 cache 어노테이션 사용법NextEhCache 사용해보기

Last updated 8 months ago