728x90
Catalogs and Orders Microservice 개요
APIs
기능 | URI(API Gateway 사용 시) | URI(API Gateway 미사용 시) | HTTP Method |
상품 목록 조회 | Catalogs Microservice | /catalog-service/catalogs | GET |
사용자 별 상품 주문 | Orders Microservice | /order-service/{user_id}/orders | POST |
사용자 별 주문 내역 조회 | Orders Microservice | /order-service/{user_id}/orders | GET |
Orders Microservice
프로젝트 생성
build.gradle
ModelMapper dependancy 추가
- maven
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.1</version>
</dependency>
- gradle
implementation 'org.modelmapper:modelmapper:2.4.2'
application.yml
server:
port: 0
spring:
application:
name: order-service
h2:
console:
enabled: true
settings:
web-allow-others: true
path: /h2-console
jpa:
hibernate:
ddl-auto: update
defer-datasource-initialization: true
datasource:
driver-class-name: org.h2.Driver
url : jdbc:h2:mem:testdb
eureka:
instance:
instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka
logging:
level:
com.example.orderservice: DEBUG
OrderEntity.java
@Data
@Entity
@Table(name = "orders")
public class OrderEntity implements Serializable {
// 직렬화를 사용하는 이유 : 가지고 있는 객체를 전송하거나 DB에 보관하기 위해 마샬링 작업을 위해 사용
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 120, unique = true)
private String productId;
@Column(nullable = false)
private Integer qty;
@Column(nullable = false)
private Integer unitPrice;
@Column(nullable = false)
private Integer totalPrice;
@Column(nullable = false)
private String userId;
@Column(nullable = false, unique = true)
private String orderId;
@Column(nullable = false, updatable = false, insertable = false)
@ColumnDefault(value = "CURRENT_TIMESTAMP")
private LocalDateTime createdAt;
}
OrderRepository.Interface
public interface OrderRepository extends CrudRepository<OrderRepository, Long> {
OrderEntity findByOrderId(String orderId);
Iterable<OrderEntity> findByUserId(String userId);
}
OrderDto.java
@Data
public class OrderDto implements Serializable {
private String productId;
private Integer qty;
private Integer unitPrice;
private Integer totalPrice;
private String orderId;
private String userId;
}
ResponseOrder.java
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseOrder {
private String productId;
private Integer qty;
private Integer unitPrice;
private Integer totalPrice;
private LocalDateTime createdAt;
private String orderId;
}
OrderService.interface
public interface OrderService {
OrderDto createOrder(OrderDto orderDetails);
OrderDto getOrderByOrderId(String orderId);
Iterable<OrderEntity> getOrdersByUserId(String userId);
}
OrderServiceImpl.java
@Service
public class OrderServiceImpl implements OrderService{
OrderRepository orderRepository;
@Autowired
public OrderServiceImpl(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@Override
public OrderDto createOrder(OrderDto orderDto) {
orderDto.setOrderId(UUID.randomUUID().toString());
orderDto.setTotalPrice(orderDto.getQty() * orderDto.getUnitPrice());
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
OrderEntity orderEntity = mapper.map(orderDto, OrderEntity.class);
orderRepository.save(orderEntity);
OrderDto returnValue = mapper.map(orderEntity, OrderDto.class);
return returnValue;
}
@Override
public OrderDto getOrderByOrderId(String orderId) {
OrderEntity orderEntity = orderRepository.findByOrderId(orderId);
OrderDto orderDto = new ModelMapper().map(orderEntity, OrderDto.class);
return orderDto;
}
@Override
public Iterable<OrderEntity> getOrdersByUserId(String orderId) {
return orderRepository.findByUserId(orderId);
}
}
OrderController
@RestController
@RequestMapping("/order-service")
public class OrderController {
Environment env;
OrderService orderService;
@Autowired
public OrderController(Environment env, OrderService orderService) {
this.env = env;
this.orderService = orderService;
}
@GetMapping("/health_check")
public String status() {
return String.format("It's Working in Catalog Service on PORT %s",
env.getProperty("local.server.port"));
}
@PostMapping("/{userId}/orders")
public ResponseEntity<ResponseOrder> createOrder(@PathVariable("userId") String userId, @RequestBody RequestOrder orderDetails) {
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
OrderDto orderDto = mapper.map(orderDetails, OrderDto.class);
orderDto.setUserId(userId);
OrderDto createdOrder = orderService.createOrder(orderDto);
ResponseOrder responseOrder = mapper.map(createdOrder, ResponseOrder.class);
return ResponseEntity.status(HttpStatus.CREATED).body(responseOrder);
}
@GetMapping("/{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);
}
}
apigatway-service
application.yml
routes:
- id: user-service
uri: lb://USER-SERVICE
predicates:
- Path=/user-service/**
- id: catalog-service
uri: lb://CATALOG-SERVICE
predicates:
- Path=/catalog-service/**
- id: order-service
uri: lb://ORDER-SERVICE
predicates:
- Path=/order-service/**
서버 가동 후 유레카 대시보드 확인
postman으로 주문 등록과 조회를 해보자..