📌설명: 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> {
}
'language > java' 카테고리의 다른 글
자바(Java)란 무엇인가 – 언어로서의 자바 첫걸음 | 한 번 작성하면 어디서나 실행되는 언어 | 플랫폼 자바런타임 (0) | 2025.04.08 |
---|---|
🧾Zipher프로토콜 - java 유틸파일 2 (0) | 2025.04.08 |
🧾Zipher 프로토콜 - 화면에서 서버REST API로 호출 (Spring 기반) (0) | 2025.04.07 |
🧾 Zipher 프로토콜 - 텍스트커맨드 통신 _ 저울라벨프린터용 _ 요청과 응답 유틸 함수 - Java 소스 샘플 (0) | 2025.04.07 |
댓글