Home [Spring] Microservices in Spring Boot
Post
Cancel

[Spring] Microservices in Spring Boot

How to communicate microservices

  • @FeignClient (ApiClient)
  • Kafka (Use Event)
  • RestTemplate (communicate with REST API)
  • Circuit Breaker (Fault Tolerant Design Pattern)

Spring Cloud

a framework for building robust cloud(strong and healthy) applications. (= microservices)

Spring Cloud Stream

A lightweight event-driven microservices framework to quickly build applications that can connect to external systems. Simple declarative model to send and receive messages using Apache Kafka(middleware) or RabbitMQ between Spring Boot apps.


@FeignClient

  • Microservices communication method in Spring Boot
  • @EnableFeignClients

user-service

build.gradle

1
2
3
dependencies {
    implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-openfeign', version: '2.1.1.RELEASE'
}

user-service

1
2
3
4
@EnableFeignClients
public class ApiClientConfiguration {
    ...
}

departments-service

1
2
3
4
5
6
7
8
@FeignClient(name = "user", contextId = "userEnvironmentSetting", url = "${...}")
@RequestMapping(path="/users", consumes = "application/json")
interface UserEnvironmentSettingClient {

    @Override
    @GetMapping("/users/environmentSetting")
    Map<String, String> getEnvironmentSetting();
}
  • name : LoadBalancer client name
  • contextId : bean name instead of name if present
    • issue : 동일 name 으둜 λ‘κ°œμ˜ class μ—μ„œ μ§€μ •ν•˜λ©΄ 였λ₯˜ λ°œμƒ
  • reference: https://techblog.woowahan.com/2630/

RestTemplate

  • Spring Http communication template (Rest API μ„œλΉ„μŠ€λ₯Ό μš”μ²­ ν›„ 응닡받을 λ•Œ 주둜 μ‚¬μš©)
  • For communiating over the microservices
  • Synchronize (Async : org.springframework.web.client.AsyncRestTemplate)
  • will be deprecated

build.gradle

1
implementation 'org.springframework.boot:spring-boot-starter-web'

RestTemplate VS WebCLient

Β RestTemplateWebCLient
Β SyncAsync (= AsyncRestTemplate)
Dependencyimplementation
β€˜org.springframework.boot:spring-boot-starter-web’
implementation
β€˜org.springframework.boot:spring-boot-starter-webflux’
  • reference

https://backtony.github.io/spring/2021-07-12-spring-basic-8/
https://blog.naver.com/hj_kim97/222295259904
https://sjh836.tistory.com/141

Blocking VS Non-Blocking VS Sync VS Async

  • Blocking / Non-blocking
    λ‹€λ₯Έ 주체가 μž‘μ—…ν•  λ•Œ μžμ‹ μ—κ²Œ μžμ‹ μ˜ μž‘μ—…μ— λŒ€ν•œ μ œμ–΄κΆŒμ΄ μžˆλŠ”μ§€ μ—†λŠ”μ§€
Β BlockingNon-blocking
 호좜된 ν•¨μˆ˜κ°€ μžμ‹ μ˜ μž‘μ—…μ„ λͺ¨λ‘ 마칠 λ•ŒκΉŒμ§€
ν˜ΈμΆœν•œ ν•¨μˆ˜μ—κ²Œ μ œμ–΄κΆŒμ„ λ„˜κ²¨μ£Όμ§€ μ•Šκ³  λŒ€κΈ°ν•˜κ²Œ λ§Œλ“ λ‹€λ©΄
(executes β€œin series”)
호좜된 ν•¨μˆ˜κ°€ λ°”λ‘œ λ¦¬ν„΄ν•΄μ„œ
ν˜ΈμΆœν•œ ν•¨μˆ˜μ—κ²Œ μ œμ–΄κΆŒμ„ λ„˜κ²¨μ£Όκ³ ,
ν˜ΈμΆœν•œ ν•¨μˆ˜κ°€ λ‹€λ₯Έ 일을 ν•  수 μžˆλŠ” 기회λ₯Ό 쀄 수 있으면
(executes in parallel)
Example직원이 μƒμ‚¬μ—κ²Œ μ„œλ₯˜λ₯Ό μ œμΆœν•˜κ³ ,
상사가 μ„œλ₯˜λ₯Ό λ‹€ 읽을 λ•ŒκΉŒμ§€ μžλ¦¬μ—μ„œ κΈ°λ‹€λ¦¬λŠ” 상황
직원이 μƒμ‚¬μ—κ²Œ μ„œλ₯˜λ₯Ό μ œμΆœν–ˆμ§€λ§Œ,
상사가 μ„œλ₯˜λ₯Ό λ‹€ 읽어볼 λ™μ•ˆ μžλ¦¬μ— κ°€μ„œ μžμ‹ μ˜ 일을 μ²˜λ¦¬ν•˜λŠ” 상황
  • Sync / Async
    그것을 μš”μ²­ν•œ μˆœμ„œκ°€ μ§€μΌœμ§€λŠ”κ°€ μ•„λ‹Œκ°€ (ν˜ΈμΆœλ˜λŠ” ν•¨μˆ˜μ˜ μž‘μ—… μ™„λ£Œ μ—¬λΆ€λ₯Ό λˆ„κ°€ 신경쓰냐)
Β SynchronousAsynchronous
Β μž‘μ—…μ„ λ™μ‹œμ— μˆ˜ν–‰ν•˜κ±°λ‚˜, λ™μ‹œμ— λλ‚˜κ±°λ‚˜, λλ‚˜λŠ” λ™μ‹œμ— μ‹œμž‘ν•¨
(κ²°κ³Όλ₯Ό λ¦¬ν„΄λ°›μ•˜μ„ λ•Œ λ°”λ‘œ κ·Έ 결과에 집쀑함 / scheduled, real-time)
μ‹œμž‘, μ’…λ£Œκ°€ μΌμΉ˜ν•˜μ§€ μ•ŠμœΌλ©° λλ‚˜λŠ” λ™μ‹œμ— μ‹œμž‘μ„ ν•˜μ§€ μ•ŠμŒ
(κ²°κ³Όλ₯Ό λ°”λ‘œ μ²˜λ¦¬ν•˜μ§€ μ•Šμ•„λ„ 됨 / on your own time, no need schedule / use callback)
Β When a work is requested,
the result value of the request is directly returned.
When a work is requested,
the result value of the request is indirectly received
Β μš”μ²­μ„ 보낸 ν›„ 응닡을 λ°›μ•„μ•Όμ§€λ§Œ λ‹€μŒ λ™μž‘μ΄ 이루어짐웹 νŽ˜μ΄μ§€ 전체λ₯Ό μƒˆλ‘œκ³ μΉ¨ ν•˜μ§€μ•Šκ³  데이터λ₯Ό λΆˆλŸ¬μ˜€λŠ” 방식
 비동기 방식에 λΉ„ν•΄ 섀계가 맀우 κ°„λ‹¨ν•˜κ³  μ§κ΄€μ μ΄μ§€λ§Œ
κ²°κ³Όκ°€ μ£Όμ–΄μ§ˆ λ•Œ κΉŒμ§€ 아무 것도 λͺ»ν•˜κ³  λŒ€κΈ°ν•΄μ•Όν•¨
비동기 방식을 μ΄μš©ν•  경우, ν•„μš”ν•œ λΆ€λΆ„μ˜ λ°μ΄ν„°λ§Œ λΆˆλŸ¬μ™€ μ‚¬μš© κ°€λŠ₯.
κ²°κ³Όκ°€ μ£Όμ–΄μ§€λŠ”λ° μ‹œκ°„μ΄ 걸리더라도
κ·Έ μ‹œκ°„λ™μ•ˆ λ‹€λ₯Έ μž‘μ—…μ„ ν•  수 μžˆμœΌλ―€λ‘œ μžμ›μ˜ 효율적 μ‚¬μš© κ°€λŠ₯
Example상사가 μ„œλ₯˜λ₯Ό λ‹€ 읽고 κ²°κ³Όλ₯Ό 리턴해주면
직원은 λ°”λ‘œ κ·Έ 결과에 관심을 κ°–κ²Œ λ©λ‹ˆλ‹€.
상사가 λ¦¬ν„΄ν•œ κ²°κ³Όλ₯Ό λ°”λ‘œ μ²˜λ¦¬ν• μ§€,
λ‚˜μ€‘μ— μ²˜λ¦¬ν• μ§€λ₯Ό κ²°μ •ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
  • common used : sync-blocking, sync-nonblocking, async-nonblocking (most efficient) img (1)

  • reference

https://studyandwrite.tistory.com/486
https://baek-kim-dev.site/38


CircuitBreaker (Design pattern using netfilx hystrix)

  • Hystrix
    library form Netflix (spring-cloud-starter-netflix), isolates the points of access between the services, stops cascading failures across thhem and provides the fallback options
    • Fallback
      provides an alternative solution during a service request failure
  • Circuit Breaker Pattern
    prevents failure cascading and gives a default behavior when services fail
    • Netflix Hystrix
      allows us to introduce fault tolerance and latency tolerance by isolating failure and by preventing them from cascading into the other part of the system building a more robust distributed application.

Screen Shot 2022-08-01 at 2 02 28 PM

Screen Shot 2022-08-01 at 2 01 15 PM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Service
public class GreetingService {

    @HystrixCommand(fallbackMethod = "defaultGreeting")
    public String getGreeting(String username) {
        return new RestTemplate()
          .getForObject("http://localhost:9090/greeting/{username}", 
          String.class, username);
    }
 
    private String defaultGreeting(String username) {
        return "Hello User!";
    }
}
  • @EnableCircuitBreaker
    will scan the classpath for any compatible Circuit Breaker implementation.
1
2
3
4
5
6
7
@SpringBootApplication
@EnableCircuitBreaker
public class RestConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(RestConsumerApplication.class, args);
    }
}

Hystrix VS Resilience4J

  • common feature : fault tolerant library
HystrixResilience4J
embraces an Object-Oriented design
where calls to external systems have to be wrapped in a HystrixCommand
offering multiple functionalities.
relies on function composition
to let you stack the specific decorators you need.

Screen Shot 2022-08-01 at 11 10 27 AM

  • reference

https://engineering.linecorp.com/ko/blog/circuit-breakers-for-distributed-services/
https://www.baeldung.com/spring-cloud-netflix-hystrix
https://digitalvarys.com/what-is-circuit-breaker-design-pattern/


API Gateway (Load balancing)

Service : Cloud-gateway

spring-cloud-starter-gateway

bulid.gradle

1
2
3
dependencies {
    compile 'org.springframework.cloud:spring-cloud-starter-gateway:2.1.0.RELEASE'
}

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
server:
    port: 9191

spring:
  cloud:
    gateway:
      routes:
        - id: USER-SERVICE
          url: ${cloud-gateway.user-url}
          predicates:
            - Path=/users/ **
        - id: DEPARTMENT-SERVICE
          url: ${cloud-gateway.department-url}
          predicates:
            - Path=/departments/ **
          filter:
            - name: CircuitBreaker
              args:
                name: USER-SERVICE
                fallbackuri: forward:/userServiceFallBack

cloud-gateway:
    user-url: http://cloud-user-service:9001
    department-url: http://cloud-department-service:9002

Meaning:

Spring-boot-starter-actuator

bulid.gradle

1
2
3
dependencies {Β 
  compile("org.springframework.boot:spring-boot-starter-actuator")
}

application.yml

From spring boot 2.x, you have to custom management part in application.yml because the default setting is not exposing most datas.

1
2
3
4
5
management:
  endpoints:
    web:
      exposure:
        include: health

Meaning : expose the health information

1
2
3
4
5
management:
    endpoints:
        web:
            exposure:
                exclude: env, beans

Meaning : expose the information except for env, beans

the property exclude is prior than include, so if you declared some information on exclude, you can’t see it even if you declared that on include.


Spring Cloud Stream

  • 이벀트 쀑심 microservcieλ₯Ό κ΅¬μΆ•ν•˜κΈ° μœ„ν•œ ν”„λ ˆμž„μ›Œν¬
  • Apache Kafka λ˜λŠ” RabbitMQ 등을 μ‚¬μš©ν•˜μ—¬ Spring Boot μ–΄ν”Œλ¦¬μΌ€μ΄μ…˜κ³Ό 메세지λ₯Ό 보내고 λ°›μŒ.

https://saramin.github.io/2019-08-28-2/


Eureke Client

This post is licensed under CC BY 4.0 by the author.

[Study] TODO

[Spring] Apache Kafka + Spring Boot

Comments powered by Disqus.