Category: Spring Cloud

0

Spring Cloud - Eureka 에 Service 등록하기

목차 Spring Cloud - Eureka 에 Service 등록하기 Spring Cloud - Service Discovery Server (Eureka) 참고 https://cloud.spring.io/spring-cloud-netflix/reference/html/ https://coe.gitbook.io/guide/service-discovery/eureka Service 등록하기implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' @EnableDiscoveryClient@SpringBootApplication@EnableDiscoveryClientpublic class UserServiceApplication { public static void main(String[] args){ SpringApplication.run(UserServiceApplication.class, args); }} Eureka 서버에 등록을 위한 Properties 설정 추가eureka.client.register-with-eureka 값을 true 로 줌으로써 Eureka 서버에 등록하도록 설정합니다.

0

Spring Cloud - Service Discovery Server (Eureka)

목차 Spring Cloud - Eureka 에 Service 등록하기 Spring Cloud - Service Discovery Server (Eureka) 참고 https://cloud.spring.io/spring-cloud-netflix/reference/html/ https://coe.gitbook.io/guide/service-discovery/eureka 사용하는 Spring Cloud 버전plugins { id 'org.springframework.boot' version '2.4.5' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java'}group = 'com.example'version = '0.0.1-SNAPSHOT'sourceCompatibility = '11'repositories { mavenCentral()}ext { set('springCloudVersion', "2020.0.2")}dependencies { testImplementation 'org.springframework.boot:spring-boot-starter-test'}dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" }}test { useJUnitPlatform()} Spring Cloud EurekaMSA (Micro Service Architecture) 에서는 각 서비스를 관리하기 위해서 Service Discovery Server 가 필요합니다. Spring Cloud 에서는 Service Discovery 를 위해 Eureka 를 사용한다. Discovery Server (Eureka)implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server'

0

Spring Cloud - 33. Order Kafka Producer

목차 Spring Cloud - 33. Order Kafka Producer Spring Cloud - 32. kafka-mariadb 연결 Spring Cloud - 31. Kafka Topic 적용 Order Kafka Producer@RestController@RequestMapping("/order-service/")@RequiredArgsConstructorpublic class OrderController { private final OrderService orderService; private final KafkaProducer kafkaProducer; private final OrderProducer orderProducer; @PostMapping(value = "/{userId}/orders") public ResponseEntity<ResponseOrder> createOrder(@PathVariable("userId") String userId, @RequestBody RequestOrder orderDetails){ ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); OrderDto orderDto = modelMapper.map(orderDetails, OrderDto.class); orderDto.setUserId(userId); orderDto.setOrderId(UUID.randomUUID().toString()); orderDto.setTotalPrice(orderDetails.getQty() * orderDetails.getUnitPrice()); ResponseOrder returnValue = modelMapper.map(orderDto, ResponseOrder.class); kafkaProducer.send("example-order-topic", orderDto); orderProducer.send("orders", orderDto); return ResponseEntity.status(HttpStatus.CREATED).body(returnValue); } @GetMapping(value = "/{userId}/orders") public ResponseEntity<List<ResponseOrder>> getOrder(@PathVariable("userId") String userId){ Iterable<OrderEntity> orderList = orderService.getOrdersByUserId(userId); List<ResponseOrder> result = new ArrayList<>(); orderList.forEach(v -> { result.add(new ModelMapper().map(v, ResponseOrder.class)); }); return ResponseEntity.status(HttpStatus.OK).body(result); }} @Service@Slf4j@RequiredArgsConstructorpublic class OrderProducer { private final KafkaTemplate<String, String> kafkaTemplate; public OrderDto send(String topic, OrderDto orderDto){ ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try{ jsonInString = mapper.writeValueAsString(orderDto); }catch (JsonProcessingException ex){ ex.printStackTrace(); } kafkaTemplate.send(topic, jsonInString); log.info("Kafka Producer sent data from the Order microservice: " + orderDto); return orderDto; }} @Data@Builderpublic class Scheme { private String type; private List<Field> fields; private boolean optional; private String name;} @Data@AllArgsConstructorpublic class Field { private String type; private boolean optional; private String field;} @Data@Builderpublic class Payload { private String order_id; private String user_id; private String product_id; private int qty; private int unit_price; private int total_price;} @Data@AllArgsConstructorpublic class KafkaOrderDto implements Serializable { private Scheme scheme; private Payload payload;}

0

Spring Cloud - 32. kafka-mariadb 연결

목차 Spring Cloud - 33. Order Kafka Producer Spring Cloud - 32. kafka-mariadb 연결 Spring Cloud - 31. Kafka Topic 적용 Config// https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-clientimplementation 'org.mariadb.jdbc:mariadb-java-client' create table users( id int auto_increment primary key, user_id varchar(20), pwd varchar(20), name varchar(20), created_at datetime default NOW()); Kafka Connect 설치curl -O http://packages.confluent.io/archive/5.5/confluent-community-5.5.2-2.12.tar.gz curl -O http://packages.confluent.io/archive/6.1/confluent-community-6.1.0.tar.gz tar xvf confluent-community-6.1.0.tar.gz

0

Spring Cloud - 31. Kafka Topic 적용

목차 Spring Cloud - 33. Order Kafka Producer Spring Cloud - 32. kafka-mariadb 연결 Spring Cloud - 31. Kafka Topic 적용 Catalog Service// https://mvnrepository.com/artifact/org.springframework.kafka/spring-kafkaimplementation 'org.springframework.kafka:spring-kafka' @EnableKafka@Configurationpublic class KafkaConsumerConfig { @Bean public ConsumerFactory<String, String> consumerFactory(){ Map<String, Object> properties = new HashMap<>(); properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); properties.put(ConsumerConfig.GROUP_ID_CONFIG, "consumerGroupId"); properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); return new DefaultKafkaConsumerFactory<>(properties); } @Bean public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(){ ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory = new ConcurrentKafkaListenerContainerFactory<>(); kafkaListenerContainerFactory = new ConcurrentKafkaListenerContainerFactory<>(); kafkaListenerContainerFactory.setConsumerFactory(consumerFactory()); return kafkaListenerContainerFactory; }} Order Service@Configurationpublic class KafkaProducerConfig { @Bean public ProducerFactory<String, String> producerFactory(){ Map<String, Object> configProps = new HashMap<>(); configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); return new DefaultKafkaProducerFactory<>(configProps); } @Bean public KafkaTemplate<String, String> kafkaTemplate(){ return new KafkaTemplate<>(producerFactory()); }} @Service@Slf4j@RequiredArgsConstructorpublic class KafkaProducer { private final KafkaTemplate<String, String> kafkaTemplate; public OrderDto send(String kafkaTopic, OrderDto orderDto){ ObjectMapper mapper = new ObjectMapper(); String jsonInString = ""; try{ jsonInString = mapper.writeValueAsString(orderDto); }catch (JsonProcessingException e){ e.printStackTrace(); } kafkaTemplate.send(kafkaTopic, jsonInString); log.info("Kafka Producer send data from the Order microservice: " + orderDto); return orderDto; }}

0

Spring Cloud - 30. Micro Service간 통신 ErrorDecoder 구현

목차 Spring Cloud - 30. Micro Service간 통신 ErrorDecoder 구현 Spring Cloud - 29. Micro Service간 통신 Feign client 예외 처리 Spring Cloud - 28. Micro Service간 통신 Feign client Spring Cloud - 27. Micro Service간 통신 ErrorDecoder 구현public class FeignErrorDecoder implements ErrorDecoder { @Override public Exception decode(String methodKey, Response response) { switch (response.status()) { case 400: break; case 404: if (methodKey.contains("getOrders")) { return new ResponseStatusException(HttpStatus.valueOf(response.status()) , "User's orders is empty."); } break; default: return new Exception(response.reason()); } return null; }} @SpringBootApplication@EnableDiscoveryClient@EnableFeignClients@Slf4jpublic class UserServiceApplication { public static void main(String[] args){ SpringApplication.run(UserServiceApplication.class, args); } @Bean public BCryptPasswordEncoder passwordEncoder() throws UnknownHostException { return new BCryptPasswordEncoder(); } @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); } @Bean public Logger.Level feignLoggerLevel(){ return Logger.Level.FULL; } @Bean public FeignErrorDecoder getFeignErrorDecoder(){ return new FeignErrorDecoder(); }} token: expiration_time: 84600000 secret: user_token_native_application_changedgateway: ip: 192.168.123.106order_service: url: http://ORDER-SERVICE/order-service/%s/orders exception: orders_is_empty: User's orders is empty. @Component@RequiredArgsConstructorpublic class FeignErrorDecoder implements ErrorDecoder { private final Environment env; @Override public Exception decode(String methodKey, Response response) { switch (response.status()) { case 400: break; case 404: if (methodKey.contains("getOrders")) { return new ResponseStatusException(HttpStatus.valueOf(response.status()) , env.getProperty("order_service.exception.orders_is_empty")); } break; default: return new Exception(response.reason()); } return null; }}

0

Spring Cloud - 29. Micro Service간 통신 Feign client 예외 처리

목차 Spring Cloud - 30. Micro Service간 통신 ErrorDecoder 구현 Spring Cloud - 29. Micro Service간 통신 Feign client 예외 처리 Spring Cloud - 28. Micro Service간 통신 Feign client Spring Cloud - 27. Micro Service간 통신 User serviceserver: port: 0spring: application: name: user-service h2: console: enabled: true settings: web-allow-others: true datasource: username: sa password: driver-class-name: org.h2.Driver url: jdbc:h2:mem:testdb rabbitmq: host: 127.0.0.1 port: 5672 username: guest password: guesteureka: instance: instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}} client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eurekagreeting: message: Welcome to the Simple E-commerce.management: endpoints: web: exposure: include: refresh, health, beans, busrefreshlogging: level: com.example.userservice.client: DEBUG#token:# expiration_time: 84600000# secret: user_token @SpringBootApplication@EnableDiscoveryClient@EnableFeignClients@Slf4jpublic class UserServiceApplication { public static void main(String[] args){ SpringApplication.run(UserServiceApplication.class, args); } @Bean public BCryptPasswordEncoder passwordEncoder() throws UnknownHostException { return new BCryptPasswordEncoder(); } @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); } @Bean public Logger.Level feignLoggerLevel(){ return Logger.Level.FULL; }} @Overridepublic UserDto getUserByUserId(String userId) { UserEntity userEntity = userRepository.findByUserId(userId); if (userEntity == null) throw new UsernameNotFoundException("User not found"); UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); List<ResponseOrder> orderList = null; try { orderList = orderServiceClient.getOrders(userId); } catch (FeignException ex) { log.error(ex.getMessage()); } userDto.setOrders(orderList); return userDto;}

0

Spring Cloud - 28. Micro Service간 통신 Feign client

목차 Spring Cloud - 30. Micro Service간 통신 ErrorDecoder 구현 Spring Cloud - 29. Micro Service간 통신 Feign client 예외 처리 Spring Cloud - 28. Micro Service간 통신 Feign client Spring Cloud - 27. Micro Service간 통신 User service// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeignimplementation 'org.springframework.cloud:spring-cloud-starter-openfeign' @SpringBootApplication@EnableDiscoveryClient@EnableFeignClients@Slf4jpublic class UserServiceApplication { public static void main(String[] args){ SpringApplication.run(UserServiceApplication.class, args); } @Bean public BCryptPasswordEncoder passwordEncoder() throws UnknownHostException { return new BCryptPasswordEncoder(); } @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); }} FeignClient의 name속성에 들어가는 값은 eureka 서버에 등록 돼 있는 Application 이름이다. @FeignClient(name = "order-service")public interface OrderServiceClient { @GetMapping("/order-service/{userId}/orders") List<ResponseOrder> getOrders(@PathVariable String userId);} @Overridepublic UserDto getUserByUserId(String userId) { UserEntity userEntity = userRepository.findByUserId(userId); if (userEntity == null) throw new UsernameNotFoundException("User not found"); UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); List<ResponseOrder> orderList = orderServiceClient.getOrders(userId); userDto.setOrders(orderList); return userDto;}

0

Spring Cloud - 27. Micro Service간 통신

목차 Spring Cloud - 30. Micro Service간 통신 ErrorDecoder 구현 Spring Cloud - 29. Micro Service간 통신 Feign client 예외 처리 Spring Cloud - 28. Micro Service간 통신 Feign client Spring Cloud - 27. Micro Service간 통신 User Service@SpringBootApplication@EnableDiscoveryClient@Slf4jpublic class UserServiceApplication { public static void main(String[] args){ SpringApplication.run(UserServiceApplication.class, args); } @Bean public BCryptPasswordEncoder passwordEncoder() throws UnknownHostException { return new BCryptPasswordEncoder(); } @Bean public RestTemplate getRestTemplate(){ return new RestTemplate(); }} @Overridepublic UserDto getUserByUserId(String userId) { UserEntity userEntity = userRepository.findByUserId(userId); if (userEntity == null) throw new UsernameNotFoundException("User not found"); UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); // List<ResponseOrder> orders = new ArrayList<>(); // userDto.setOrders(orders); String orderUrl = String.format(env.getProperty("order_service.url"), userId); ResponseEntity<List<ResponseOrder>> orderListResponse = restTemplate.exchange(orderUrl , HttpMethod.GET , null , new ParameterizedTypeReference<List<ResponseOrder>>() {}); List<ResponseOrder> orderList = orderListResponse.getBody(); userDto.setOrders(orderList); return userDto;} application.ymltoken: expiration_time: 84600000 secret: user_token_native_application_changedgateway: ip: 192.168.123.106order_service: url: http://127.0.0.1:8080/order-service/%s/orders token: expiration_time: 84600000 secret: user_token_native_application_changedgateway: ip: 192.168.123.106order_service: url: http://ORDER-SERVICE/order-service/%s/orders @SpringBootApplication@EnableDiscoveryClient@Slf4jpublic class UserServiceApplication { public static void main(String[] args){ SpringApplication.run(UserServiceApplication.class, args); } @Bean public BCryptPasswordEncoder passwordEncoder() throws UnknownHostException { return new BCryptPasswordEncoder(); } @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); }}

0

Spring Cloud - 26. Spring Cloud Bus

Config Server// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuatorimplementation 'org.springframework.boot:spring-boot-starter-actuator' // https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-bus-amqpimplementation 'org.springframework.cloud:spring-cloud-starter-bus-amqp' Users Microservice// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-bus-amqpimplementation 'org.springframework.cloud:spring-cloud-starter-bus-amqp' Gateway Service// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-bus-amqpimplementation 'org.springframework.cloud:spring-cloud-starter-bus-amqp' Config Serverserver: port: 8888spring: application: name: config-service profiles: active: native cloud: config: server: native: search-locations: file://${user.home}/dev/study/Spring-Cloud/gateway/git-local-repository rabbitmq: host: 127.0.0.1 port: 5672 username: guest password: guestmanagement: endpoints: web: exposure: include: health, busrefresh#spring:# application:# name: config-service# cloud:# config:# server:# git:# uri: https://github.com/ckck803/spring-cloud-config## uri: file:///Users/dongwoo-yang/dev/study/Spring-Cloud/gateway/git-local-repository User Service

0

Spring Cloud - 25. Spring Cloud Config Native

목차 Spring Cloud - 25. Spring Cloud Config Native Spring Cloud - 24. Client Service 에서 Config Server 연동하기 Spring Cloud - 23. Spring Cloud Config Server 만들기 Spring Cloud - 22. Spring Cloud Config 연동 Actuator 2 Spring Cloud - 21. Spring Cloud Config 연동 Actuactor server: port: 8888spring: application: name: config-service profiles: active: native cloud: config: server: native: search-locations: file://${user.home}/dev/study/Spring-Cloud/gateway/git-local-repository#spring:# application:# name: config-service# cloud:# config:# server:# git:# uri: https://github.com/ckck803/spring-cloud-config## uri: file:///Users/dongwoo-yang/dev/study/Spring-Cloud/gateway/git-local-repository

0

Spring Cloud - 24. Client Service 에서 Config Server 연동하기

목차 Spring Cloud - 25. Spring Cloud Config Native Spring Cloud - 24. Client Service 에서 Config Server 연동하기 Spring Cloud - 23. Spring Cloud Config Server 만들기 Spring Cloud - 22. Spring Cloud Config 연동 Actuator 2 Spring Cloud - 21. Spring Cloud Config 연동 Actuactor Client Service 에서 Config Server 로부터 Config 파일 읽어오기// 외부 Config를 가져오기 위한 Dependency 설정implementation 'org.springframework.cloud:spring-cloud-config-server'implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap' spring: cloud: config: uri: http://127.0.0.1:8888 name: ecommerce profiles: active: dev spring: cloud: config: uri: http://127.0.0.1:8888 name: ecommerce profiles: active: prod

0

Spring Cloud - 23. Spring Cloud Config Server 만들기

목차 Spring Cloud - 25. Spring Cloud Config Native Spring Cloud - 24. Client Service 에서 Config Server 연동하기 Spring Cloud - 23. Spring Cloud Config Server 만들기 Spring Cloud - 22. Spring Cloud Config 연동 Actuator 2 Spring Cloud - 21. Spring Cloud Config 연동 Actuactor Spring Cloud Config Server 의존성 추가// 외부 Config를 가져오기 위한 Dependency 설정implementation 'org.springframework.cloud:spring-cloud-config-server'implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap' Config Server 만들기@EnableConfigServer 어노테이션을 추가하여 Config Server를 만들어 준다. @SpringBootApplication@EnableConfigServerpublic class ConfigServiceApplication { public static void main(String[] args) { SpringApplication.run(ConfigServiceApplication.class, args); }} Config 파일 읽어오기Config 파일 위치에 따라서 Spring Cloud Config Server 에서 Config 파일을 읽어오는 방식이 달라진다.

0

Spring Cloud - 22. Spring Cloud Config 연동 Actuator 2

목차 Spring Cloud - 25. Spring Cloud Config Native Spring Cloud - 24. Client Service 에서 Config Server 연동하기 Spring Cloud - 23. Spring Cloud Config Server 만들기 Spring Cloud - 22. Spring Cloud Config 연동 Actuator 2 Spring Cloud - 21. Spring Cloud Config 연동 Actuactor Spring Cloud로 개발하는 마이크로서비스 애플리케이션 22 - Spring Cloud Config 연동 Actuator 2// 외부 Config를 가져오기 위한 Dependency 설정implementation 'org.springframework.cloud:spring-cloud-starter-config'implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap'// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuatorimplementation 'org.springframework.boot:spring-boot-starter-actuator' spring: cloud: config: uri: http://127.0.0.1:8888 name: ecommerce @SpringBootApplicationpublic class ApigatewayServiceApplication { public static void main(String[] args) { SpringApplication.run(ApigatewayServiceApplication.class, args); } @Bean public HttpTraceRepository httpTraceRepository(){ return new InMemoryHttpTraceRepository(); }} server: port: 8080eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eurekaspring: application: name: apigateway-service cloud: gateway: default-filters: - name: GlobalFilter args: baseMessage: Spring Cloud Gateway Global Filter preLogger: true postLogger: true routes:# - id: user-service# uri: lb://USER-SERVICE# predicates:# - Path=/user-service/**# filters:# - CustomFilter - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/login - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/users - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/** - Method=GET filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - AuthorizationHeaderFilter - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/actuator/** - Method=GET, POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: catalog-service uri: lb://CATALOG-SERVICE predicates: - Path=/catalog-service/** filters: - CustomFilter - id: order-service uri: lb://ORDER-SERVICE predicates: - Path=/order-service/** filters: - CustomFiltertoken: secret: user_tokenmanagement: endpoints: web: exposure: include: refresh, health, beans, httptrace

0

Spring Cloud - 21. Spring Cloud Config 연동 Actuactor

목차 Spring Cloud - 25. Spring Cloud Config Native Spring Cloud - 24. Client Service 에서 Config Server 연동하기 Spring Cloud - 23. Spring Cloud Config Server 만들기 Spring Cloud - 22. Spring Cloud Config 연동 Actuator 2 Spring Cloud - 21. Spring Cloud Config 연동 Actuactor 참고 https://www.baeldung.com/spring-cloud-config-without-git https://mangkyu.tistory.com/253 Spring Cloud Config ServerSpring Cloud Config Server 의존성 추가// 외부 Config를 가져오기 위한 Dependency 설정implementation 'org.springframework.cloud:spring-cloud-config-server'implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap' /{application}/{profile}[/{label}]/{application}-{profile}.yml/{label}/{application}-{profile}.yml/{application}-{profile}.properties/{label}/{application}-{profile}.properties @EnableConfigServer 어노테이션을 추가하여 Config Server를 만들어 준다.