SpringBoot 를 배워보자

UN/EDIFACT 메시지를 처리하는 웹 서비스를 구현

_Blue_Sky_ 2024. 10. 21. 16:26
728x90
728x90

 

package com.example.edifact;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.ArrayList;

@SpringBootApplication
public class EdifactApplication {
    public static void main(String[] args) {
        SpringApplication.run(EdifactApplication.class, args);
    }
}

@Data
class EdifactRequest {
    private String edifactMessage;
}

@Data
class EdifactResponse {
    private List<SegmentData> segments;
    private String status;
    private String message;
}

@Data
class SegmentData {
    private String segmentTag;
    private List<String> elements;
}

@Service
@Slf4j
class EdifactService {
    private final EdifactParser parser = new EdifactParser();

    public EdifactResponse parseEdifactMessage(String message) {
        try {
            EdifactParser.EdifactMessage parsedMessage = parser.parseMessage(message);
            EdifactResponse response = new EdifactResponse();
            List<SegmentData> segments = new ArrayList<>();

            for (EdifactParser.EdifactSegment segment : parsedMessage.getSegments()) {
                SegmentData segmentData = new SegmentData();
                segmentData.setSegmentTag(segment.getSegmentTag());
                segmentData.setElements(segment.getDataElements());
                segments.add(segmentData);
            }

            response.setSegments(segments);
            response.setStatus("success");
            response.setMessage("Message parsed successfully");
            return response;
        } catch (Exception e) {
            log.error("Error parsing EDIFACT message", e);
            EdifactResponse response = new EdifactResponse();
            response.setStatus("error");
            response.setMessage("Failed to parse EDIFACT message: " + e.getMessage());
            return response;
        }
    }

    public String buildEdifactMessage(List<SegmentData> segments) {
        EdifactParser.EdifactMessage message = new EdifactParser.EdifactMessage();
        
        for (SegmentData segmentData : segments) {
            EdifactParser.EdifactSegment segment = 
                new EdifactParser.EdifactSegment(segmentData.getSegmentTag());
            for (String element : segmentData.getElements()) {
                segment.addDataElement(element);
            }
            message.addSegment(segment);
        }

        return parser.buildMessage(message);
    }
}

@RestController
@RequestMapping("/api/edifact")
@Slf4j
class EdifactController {
    private final EdifactService edifactService;

    public EdifactController(EdifactService edifactService) {
        this.edifactService = edifactService;
    }

    @PostMapping("/parse")
    public ResponseEntity<EdifactResponse> parseMessage(@RequestBody EdifactRequest request) {
        log.info("Received EDIFACT message for parsing");
        EdifactResponse response = edifactService.parseEdifactMessage(request.getEdifactMessage());
        return ResponseEntity.ok(response);
    }

    @PostMapping("/build")
    public ResponseEntity<String> buildMessage(@RequestBody List<SegmentData> segments) {
        log.info("Received request to build EDIFACT message");
        String message = edifactService.buildEdifactMessage(segments);
        return ResponseEntity.ok(message);
    }
}
# application.yml
server:
  port: 8080
  servlet:
    context-path: /

spring:
  application:
    name: edifact-service

logging:
  level:
    com.example.edifact: DEBUG
    org.springframework: INFO

 

728x90

이 SpringBoot 애플리케이션의 주요 특징을 설명드리겠습니다:

  1. 주요 컴포넌트:
    • EdifactController: REST API 엔드포인트 제공
    • EdifactService: EDIFACT 메시지 처리 로직
    • EdifactParser: 이전에 구현한 EDIFACT 파서
  2. 제공하는 API 엔드포인트:
    • POST /api/edifact/parse: EDIFACT 메시지 파싱
    • POST /api/edifact/build: EDIFACT 메시지 생성
  3. 사용 예시:

메시지 파싱 요청:

curl -X POST http://localhost:8080/api/edifact/parse \
-H "Content-Type: application/json" \
-d '{
  "edifactMessage": "UNB+UNOC:3+SENDER+RECEIVER+20240321:1234+12345'\''UNH+1+ORDERS:D:96A:UN'\''"
}'

메시지 생성 요청:

curl -X POST http://localhost:8080/api/edifact/build \
-H "Content-Type: application/json" \
-d '[
  {
    "segmentTag": "UNB",
    "elements": ["UNOC:3", "SENDER", "RECEIVER", "20240321:1234", "12345"]
  },
  {
    "segmentTag": "UNH",
    "elements": ["1", "ORDERS:D:96A:UN"]
  }
]'
추가 기능으로 확장 가능한 부분:
// 메시지 유효성 검사 추가
@Validated
class EdifactRequest {
    @NotBlank(message = "EDIFACT message cannot be empty")
    private String edifactMessage;
}

// 캐싱 추가
@Service
@CacheConfig(cacheNames = {"edifact"})
class EdifactService {
    @Cacheable(key = "#message")
    public EdifactResponse parseEdifactMessage(String message) {
        // ... 기존 코드
    }
}

// 비동기 처리 추가
@Service
class EdifactService {
    @Async
    public CompletableFuture<EdifactResponse> parseEdifactMessageAsync(String message) {
        return CompletableFuture.completedFuture(parseEdifactMessage(message));
    }
}
 
  1. 보안 강화 방안:
    • Spring Security 추가
    • API 키 인증
    • Rate Limiting 구현
    • 입력 유효성 검사 강화
  2. 모니터링 및 로깅:
    • Actuator 엔드포인트 추가
    • Prometheus/Grafana 메트릭 수집
    • ELK 스택 연동

 

728x90
728x90