본문 바로가기

Programming!

Spring + Resilience4j + Redis Cache, LocalCache 사용

Docker

다중 Redis 적용도 해볼겸 redis1, redis2로 처리.

version: '3.1'

services:
  mysql:
    image: mysql:8.0.27
    command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci
    container_name: kotlin-spring-boot-study_db0
    ports:
    - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
      TZ: "Asia/Seoul"
    volumes:
    - mysql_data:/var/lib/mysql
    networks:
    - esnet
    mem_reservation: 1g
  redis1:
    container_name: kotlin-spring-boot-study_redis0
    command: redis-server --port 6379
    hostname: redis-server
    image: redis:6.2.6
    ports:
      - "6566:6379"
    mem_reservation: 1g
    networks:
      - esnet
  redis2:
    container_name: kotlin-spring-boot-study_redis1
    command: redis-server --port 6379
    hostname: redis-server
    image: redis:6.2.6
    ports:
      - "6567:6379"
    mem_reservation: 1g
    networks:
      - esnet
volumes:
  mysql_data:
    driver: local
networks:
  esnet:

 

 

build.gradle.kts

로컬캐시를 위한 caffeine도 추가

...
api("org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j")
api("com.github.ben-manes.caffeine:caffeine")
...

yml

서킷 설정 ( 참고 : https://resilience4j.readme.io/docs/getting-started-3 )

....  
  circuitbreaker:
    instances:
      default_circuit_cachedFindById:
        failure-rate-threshold: 60
        recordExceptions:
          - java.net.SocketTimeoutException
          - java.net.ConnectException
        ignoreExceptions:
          - java.lang.IllegalStateException
....

 

Code

@CircuitBreaker 지정 - 메소드 실행 실패시 fallbackMethod 실행 

( 주 : RedisConnection Exception만 서킷으로 돌리고 싶은경우 recordExceptions 에 추가. 즉,  recordExceptions와 ignoreExceptions 관리.)

....    
    @CircuitBreaker(name = "default_circuit_cachedFindById", fallbackMethod = "localCachedFindByIdFallback")
    @Cacheable(value = ["cached_dic_by_id"], key = "#id")
    fun findById(id: Long): DicResponse {
        log.info { "레디스캐시로 저장됩니다." }
        return kotlin.runCatching { dicService.findById(id) }
            .map { DicMapper.toResponse(it) }
            .getOrThrow()
    }

    private fun localCachedFindByIdFallback(id: Long, e: Exception): DicResponse {
        log.info { "로컬캐시로 전환되었습니다." }
        return dicLocalCacheableService.findById(id)
    }
....

정상호출의 경우

캐시용 레디스를 내려본다.

로컬캐시로 전환된다. ( fallbackMethod 실행됨 )

 

전체 코드 :

https://github.com/KimHyeongi/KotlinSpringboot-Tips

 

GitHub - KimHyeongi/KotlinSpringboot-Tips: KotlinSpringboot-Tips

KotlinSpringboot-Tips. Contribute to KimHyeongi/KotlinSpringboot-Tips development by creating an account on GitHub.

github.com