본문 바로가기
language/java

🧾Zipher프로토콜 - java 유틸파일 3

by 죄니안죄니 2025. 4. 8.

📌설명: zipher프로토콜 기반으로 만든 java유틸파일. OOP 스타일 기능별로 클래스 분리. 살을 더 붙인 3번째 버전

 

📌 문서 설명 요약

파일 역할
ZipherServiceApplication Spring Boot 진입점
ZipherService SLA 명령 생성, 프린터 전송, 응답 파싱, 재시도, 로그 저장, 알림 처리
ZipherSocketClient 실제 TCP/IP 소켓 통신 처리
NotificationService 실패 시 알림 전송 처리
ZipherLogEntity 로그 저장용 JPA 엔티티
ZipherLogRepository 로그 DB 접근 레이어

✅ 클레스와 메서드  

📁 ZipherServiceApplication.java

// 📁 ZipherServiceApplication.java
// Spring Boot 기반 Zipher 라벨 인쇄 시스템
// ➤ 기능: 프린터 명령 전송 + 응답 처리 + 재시도 + DB 로그 저장 + 알림 전송

package com.example.zipher;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

📁 ZipherService.java

// 📁 ZipherService.java
package com.example.zipher.service;

import com.example.zipher.protocol.ResponseType;
import com.example.zipher.protocol.ZipherResponseDispatcher;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * SLA 명령어를 생성해 Zipher 프린터로 전송하고,
 * 응답을 파싱하여 성공 여부를 판단하며, 실패 시 재시도 + 알림을 처리함.
 * 모든 결과는 DB에 저장됨.
 */
@Service
@RequiredArgsConstructor
public class ZipherService {

    private final ZipherSocketClient client;
    private final ZipherLogRepository logRepository;
    private final NotificationService notificationService;

    public void printLabel(String jobName, Map<String, String> fields) {
        String command = buildSlaCommand(jobName, fields);
        String response = null;
        int retry = 0;
        boolean success = false;

        while (retry < 3 && !success) {
            try {
                // 프린터로 명령 전송 및 응답 수신
                response = client.send(command, StandardCharsets.UTF_16LE);
                // 응답 분기 처리
                ZipherResponseDispatcher.dispatch(response);
                // 성공 여부 판별
                ResponseType type = ResponseType.from(response);
                success = (type == ResponseType.ACK || type == ResponseType.STS);
            } catch (Exception e) {
                response = "EXCEPTION: " + e.getMessage();
            }

            if (!success) {
                retry++;
                System.err.println("재시도 " + retry + "회...");
            }
        }

        // 결과 로그 저장
        logRepository.save(ZipherLogEntity.builder()
                .jobName(jobName)
                .sentCommand(command)
                .response(response)
                .success(success)
                .createdAt(LocalDateTime.now())
                .build());

        // 실패 시 알림 전송
        if (!success) {
            notificationService.send("📢 Zipher 라벨 출력 실패: " + jobName);
        }
    }

    // SLA 명령어 문자열 생성
    private String buildSlaCommand(String job, Map<String, String> fields) {
        StringBuilder sb = new StringBuilder("SLA|").append(job);
        fields.forEach((k, v) -> sb.append("|").append(k).append("=").append(v));
        return sb.append("\r").toString();
    }
}

📁 ZipherSocketClient.java

// 📁 ZipherSocketClient.java
package com.example.zipher.service;

import org.springframework.stereotype.Component;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * Zipher 프린터와 TCP/IP로 직접 통신하는 컴포넌트
 */
@Component
public class ZipherSocketClient {
    private final String printerIp = "192.168.0.100";
    private final int printerPort = 3003;

    public String send(String command, Charset charset) throws IOException {
        try (Socket socket = new Socket(printerIp, printerPort);
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset));
             BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), charset))) {

            writer.write(command);
            writer.flush();
            return reader.readLine();
        }
    }
}

📁 NotificationService.java

// 📁 NotificationService.java
package com.example.zipher.service;

import org.springframework.stereotype.Service;

/**
 * 출력 실패 시 알림을 전송하는 컴포넌트 (Slack, Email 등으로 확장 가능)
 */
@Service
public class NotificationService {
    public void send(String message) {
        // TODO: Slack, 이메일, SMS 연동 시 구현
        System.out.println("🔔 알림: " + message);
    }
}

📁 ZipherLogEntity.java

// 📁 ZipherLogEntity.java
package com.example.zipher.entity;

import jakarta.persistence.*;
import lombok.*;

import java.time.LocalDateTime;

/**
 * Zipher 명령 전송 및 응답 로그를 DB에 저장하기 위한 엔티티
 */
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ZipherLogEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String jobName;
    private String sentCommand;
    private String response;
    private boolean success;
    private LocalDateTime createdAt;
}

📁 ZipherLogRepository.java

// 📁 ZipherLogRepository.java
package com.example.zipher.repository;

import com.example.zipher.entity.ZipherLogEntity;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * 로그 저장용 JPA Repository
 */
public interface ZipherLogRepository extends JpaRepository<ZipherLogEntity, Long> {
}

 

댓글