Skip to content

Commit

Permalink
Merge pull request #14 from sazzeo/resilience4j
Browse files Browse the repository at this point in the history
Resilience4j
  • Loading branch information
sazzeo authored Aug 22, 2022
2 parents 6e4d423 + 479eb4e commit 1e8071d
Show file tree
Hide file tree
Showing 17 changed files with 79 additions and 980 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ bin/
out/
!**/src/main/**/out/
!**/src/test/**/out/
.idea

### NetBeans ###
/nbproject/private/
Expand Down
26 changes: 0 additions & 26 deletions .idea/compiler.xml

This file was deleted.

28 changes: 0 additions & 28 deletions .idea/gradle.xml

This file was deleted.

20 changes: 0 additions & 20 deletions .idea/jarRepositories.xml

This file was deleted.

8 changes: 0 additions & 8 deletions .idea/misc.xml

This file was deleted.

6 changes: 0 additions & 6 deletions .idea/vcs.xml

This file was deleted.

796 changes: 0 additions & 796 deletions .idea/workspace.xml

This file was deleted.

2 changes: 2 additions & 0 deletions d-order-service/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-config'
implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap:3.1.3'
implementation 'org.springframework.kafka:spring-kafka:2.9.0' //카프카
implementation 'org.springframework.cloud:spring-cloud-starter-sleuth:3.1.3' //sleuth
implementation 'org.springframework.cloud:spring-cloud-starter-zipkin:2.2.8.RELEASE' //zipkin


runtimeOnly 'com.h2database:h2' //runtime scope로 실행
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.example.dorderservice.vo.RequestOrder;
import com.example.dorderservice.vo.ResponseOrder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
Expand All @@ -17,6 +18,7 @@
import java.util.List;
import java.util.UUID;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/")
Expand All @@ -42,31 +44,40 @@ public String status() {
public ResponseEntity<ResponseOrder> addOrder(@PathVariable String userId
, @RequestBody RequestOrder requestOrder) {
requestOrder.setUserId(userId);

log.info("Before retrieved added microservice");
OrderDto orderDto = modelMapper.map(requestOrder , OrderDto.class);
orderDto.setOrderId(UUID.randomUUID().toString());
orderDto.setTotalPrice(orderDto.getQty() * orderDto.getUnitPrice());

//catalog 정보 업데이트
kafkaCatalogProducerService.send("example-catalog-topic" , orderDto);
// kafkaCatalogProducerService.send("example-catalog-topic" , orderDto);

kafkaOrderProducerService.send("orders" ,orderDto);
//order 정보 kafka로 업데이트
// kafkaOrderProducerService.send("orders" ,orderDto);

/* jpa 이용하는 코드*/
// orderService.createOrder(orderDto);


orderService.createOrder(orderDto);


ResponseOrder responseOrder = modelMapper.map(orderDto , ResponseOrder.class );

log.info("After retrieved added microservice");
return ResponseEntity.status(HttpStatus.CREATED).body(responseOrder);
}

//주문 확인
@GetMapping("/{userId}/orders")
public ResponseEntity< List<ResponseOrder>> findOrder(@PathVariable String userId) {
public ResponseEntity< List<ResponseOrder>> findOrder(@PathVariable String userId) throws Exception{
log.info("Before retrieved orders microservice");
List<ResponseOrder> responseOrder = orderService.findOrdersByUserId(userId);
log.info("After retrieved orders microservice");

try {

Thread.sleep(1000);
throw new Exception("장애발생");
} catch (InterruptedException e) {
log.warn(e.getMessage());
}
return ResponseEntity.status(HttpStatus.ACCEPTED).body(responseOrder);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
@Service
public class KafkaCatalogProducerService {


//order service => catalog service로 데이터 전송하기
private final KafkaTemplate kafkaTemplate;
private final ObjectMapper objectMapper;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
@Service
public class KafkaOrderProducerService {

//order service => postgre 로 데이터 전송
private final KafkaTemplate kafkaTemplate;
private final ObjectMapper objectMapper;

Expand Down
22 changes: 7 additions & 15 deletions d-order-service/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
#server:
# port: 0

spring:
application:
name: order-service
# h2:
# console:
# enabled: true
# settings:
# web-allow-others: true
# path: /h2-console
zipkin:
base-url: http://127.0.0.1:9411
compression:
enabled: true
sleuth:
sampler:
probability: 1.0 #로그 보내는 확률 1.0 => 100% 다 보내기
jpa:
hibernate:
ddl-auto: update
# datasource:
# url: jdbc:postgresql://spring-boot-study.cchzqclxtrke.ap-northeast-2.rds.amazonaws.com:5432/postgres
# username: jylim
# password: "!Tjs24fkdlwm"
# hikari:
# schema: msa_study #스키마 따로 지정하기옵션

eureka:
instance:
Expand Down
6 changes: 4 additions & 2 deletions d-user-service/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ dependencies {
// implementation 'org.springframework.cloud:spring-cloud-starter-bus-amqp:3.1.2'

//openfeign
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign:3.1.3'
implementation 'org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j:2.1.3'
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign:3.1.3' //open feign
implementation 'org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j:2.1.3' //resilience4j
implementation 'org.springframework.cloud:spring-cloud-starter-sleuth:3.1.3' //sleuth
implementation 'org.springframework.cloud:spring-cloud-starter-zipkin:2.2.8.RELEASE' //zipkin

implementation 'org.postgresql:postgresql:42.3.6'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,47 @@
package com.example.duserservice.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;


@Configuration
public class Resilience4JConfig {


//얘를 만들게 되면 CircuitBreakerFactory에 자동 구현됨.
//Customizer :
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> globalCustomConfiguration() {

CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.failureRateThreshold(4)
.waitDurationInOpenState(Duration.ofMillis(1000))
.slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
.slidingWindowSize(2)
.build();

TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
.timeoutDuration(Duration.ofSeconds(4))
.build();

return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
.timeLimiterConfig(timeLimiterConfig)
.circuitBreakerConfig(circuitBreakerConfig)
.build());

}

// @Bean
// public Customizer<Resilience4JCircuitBreakerFactory> globalCustomConfiguration() {
// return factory -> factory.configureDefault(id->new Resilience4JConfigBuilder(id)
// .timeLimiterConfig()
// .circuitBreakerConfig(circuitBreakerConfig)
// .build());
//
// public Customizer<ObjectMapper> objectMapper() {
// return factory -> new ObjectMapper();
// }

}
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,14 @@ public UserDto findUserByUserId(String userId) {

UserDto userDto = modelMapper.map(userEntity, UserDto.class);


log.info("Before call orders microservice");
CircuitBreaker circuitBreaker = circuitBreakerFactory.create("circuitBreaker"); //서킷 브레이커 이름

List<ResponseOrder> orderList = circuitBreaker.run(()-> orderServiceClient.getOrders(userId) ,
throwable -> new ArrayList<>());

log.info("After call orders microservice");

userDto.setOrders(orderList);

return userDto;
Expand Down
39 changes: 7 additions & 32 deletions d-user-service/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,41 +1,17 @@
#server:
# port: 0 # port번호 0 : 랜덤 포트를 사용하겠다는 의미
# #port: 9001 #클라이언트 포트
spring:
application:
name: user-service
jpa:
hibernate:
ddl-auto: update
# datasource:
# url: jdbc:postgresql://spring-boot-study.cchzqclxtrke.ap-northeast-2.rds.amazonaws.com:5432/postgres
# username: jylim
# password: "!Tjs24fkdlwm"
# hikari:
# schema: msa_study #스키마 따로 지정하기옵션
zipkin:
base-url: http://127.0.0.1:9411
compression:
enabled: true
sleuth:
sampler:
probability: 1.0 #로그 보내는 확률 1.0 => 100% 다 보내기

#spring:
# application:
# name: user-service #각각 마이크로 서비스마다 부여할 고유 아이디(중복 불가) => 유레카에 대문자로 등록됨. (대소문자 구분x)
# h2:
# console:
# enabled: true
# settings:
# web-allow-others: true
# path: /h2-console
# datasource: # 암호화 후 config server에 옮김
# url: jdbc:h2:mem:testdb
# driver-class-name: org.h2.Driver

# rabbitmq 정보

# rabbitmq: #호스트 정보 기술 => ms는 클라이언트
# host: 127.0.0.1
# port: 5672 # 15672 는 rabbit mq 관리 페이지 접속용
# username: guest
# password: guest

#유레카 클라이언트 역할 기능 켜기
eureka:
instance:
instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}} #인스턴스 id 부여해주기 (포트가 같을 때)
Expand All @@ -45,7 +21,6 @@ eureka:
service-url:
defaultZone: http://127.0.0.1:8761/eureka #유레카 서버의 위치를 등록함


logging:
level:
com.example.duserservice: INFO
Expand Down
Loading

0 comments on commit 1e8071d

Please sign in to comment.