From 5d34abac5bcce1808a344ae60ee17cfc1482308c Mon Sep 17 00:00:00 2001 From: 18110972313 <780768673@qq.com> Date: Sat, 24 May 2025 15:17:34 +0800 Subject: [PATCH] =?UTF-8?q?add=201.=E6=96=B0=E5=A2=9E=E6=96=B0=E6=96=99?= =?UTF-8?q?=E5=8F=B7=E6=A0=87=E7=AD=BE=E6=89=93=E5=8D=B0=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=202.=E5=A2=9E=E5=8A=A0RabbitMq=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../config/db/oracle.properties | 7 +- .../com/cim/idm/config/RabbitMqConfigNew.java | 131 ++++++ .../cim/idm/constants/RabbitMqConstants.java | 31 ++ .../cim/idm/controller/LabelController.java | 30 ++ .../java/com/cim/idm/model/LabelPrintPET.java | 44 ++ .../idm/service/Impl/BSLabelServiceImpl.java | 445 +++++++++++++++++- .../idm/service/Impl/LabelServiceImpl.java | 11 + .../service/Impl/RabbitMqServiceNewImpl.java | 45 ++ .../com/cim/idm/service/LabelService.java | 5 +- .../com/cim/idm/service/RabbitMqService.java | 22 + .../java/com/cim/idm/utils/IRequester.java | 20 + .../com/cim/idm/utils/RabbitMqUtilsNew.java | 103 ++++ .../com/cim/idm/utils/RabbitRequester.java | 267 +++++++++++ 13 files changed, 1155 insertions(+), 6 deletions(-) create mode 100644 zi-wms-pda/src/main/java/com/cim/idm/config/RabbitMqConfigNew.java create mode 100644 zi-wms-pda/src/main/java/com/cim/idm/constants/RabbitMqConstants.java create mode 100644 zi-wms-pda/src/main/java/com/cim/idm/model/LabelPrintPET.java create mode 100644 zi-wms-pda/src/main/java/com/cim/idm/service/Impl/RabbitMqServiceNewImpl.java create mode 100644 zi-wms-pda/src/main/java/com/cim/idm/service/RabbitMqService.java create mode 100644 zi-wms-pda/src/main/java/com/cim/idm/utils/IRequester.java create mode 100644 zi-wms-pda/src/main/java/com/cim/idm/utils/RabbitMqUtilsNew.java create mode 100644 zi-wms-pda/src/main/java/com/cim/idm/utils/RabbitRequester.java diff --git a/zi-wms-environment/config/db/oracle.properties b/zi-wms-environment/config/db/oracle.properties index a761665..4772909 100644 --- a/zi-wms-environment/config/db/oracle.properties +++ b/zi-wms-environment/config/db/oracle.properties @@ -20,4 +20,9 @@ db.Tst.password=adm2024 #Section 4 - Customer Prod DB Info db.Prd.url=jdbc:oracle:thin:@192.168.1.73:1526/test db.Prd.username=ziwms_sap_test -db.Prd.password=adm2024 \ No newline at end of file +db.Prd.password=adm2024 +#MQ +mq.url=192.168.1.73:5672 +mq.username=zimes +mq.password=adm2024 +mq.virtual-host=/zimes \ No newline at end of file diff --git a/zi-wms-pda/src/main/java/com/cim/idm/config/RabbitMqConfigNew.java b/zi-wms-pda/src/main/java/com/cim/idm/config/RabbitMqConfigNew.java new file mode 100644 index 0000000..c8373fd --- /dev/null +++ b/zi-wms-pda/src/main/java/com/cim/idm/config/RabbitMqConfigNew.java @@ -0,0 +1,131 @@ +package com.cim.idm.config; + + +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; + +/* +* + * @Description: + * @param + * @Return: + * @Author: Zgg + * @Date: 2024/4/13 10:43 +*/ + + + +@Slf4j +@Configuration +public class RabbitMqConfigNew { + + @Autowired + private CachingConnectionFactory connectionFactory; + + /** + * 申明接收交换机 + * @Author 10946091 + * @Date 14:32 2024/5/23 + * @Param [] + * @return org.springframework.amqp.core.Exchange + **/ +// @Bean(RabbitMqConstants.EXCHANGE_EQtoMES) +// public Exchange exchange1(){ +// //durable(true) 持久化,mq重启之后交换机还在 +// return ExchangeBuilder.topicExchange(RabbitMqConstants.EXCHANGE_EQtoMES).durable(true).autoDelete().build(); +// } +// +// @Bean(RabbitMqConstants.EXCHANGE_MEStoEQ) +// public Exchange exchange2(){ +// //durable(true) 持久化,mq重启之后交换机还在 +// return ExchangeBuilder.topicExchange(RabbitMqConstants.EXCHANGE_MEStoEQ).durable(true).autoDelete().build(); +// } +// +///** +// * 声明队列 +// * new Queue(QUEUE_EMAIL,true,false,false) +// * durable="true" 持久化 rabbitmq重启的时候不需要创建新的队列 +// * auto-delete 表示消息队列没有在使用时将被自动删除 默认是false +// * exclusive 表示该消息队列是否只在当前connection生效,默认是false +// * */ +// +// @Bean(RabbitMqConstants.EQtoMES_QUEUE) +// public Queue esQueue() { +// return new Queue(RabbitMqConstants.EQtoMES_QUEUE,true, false, true); +// } +// +// @Bean(RabbitMqConstants.EQtoMES_REPLY_QUEUE) +// public Queue esQueue2() { +// return new Queue(RabbitMqConstants.EQtoMES_REPLY_QUEUE,true, false, true); +// } +// +///* +//* +// * 声明队列 +//*/ +// +// +// @Bean(RabbitMqConstants.MEStoEQ_QUEUE) +// public Queue gitalkQueue() { +// return new Queue(RabbitMqConstants.MEStoEQ_QUEUE,true, false, true); +// } +// +// @Bean(RabbitMqConstants.MEStoEQ_REPLY_QUEUE) +// public Queue gitalkQueue2() { +// return new Queue(RabbitMqConstants.MEStoEQ_REPLY_QUEUE,true, false, true); +// } +// +///** +// * TEST1_QUEUE队列绑定交换机,指定routingKey*/ +// +// +// +// @Bean +// public Binding bindingEs(@Qualifier(RabbitMqConstants.EQtoMES_QUEUE) Queue queue, +// @Qualifier(RabbitMqConstants.EXCHANGE_EQtoMES) Exchange exchange) { +// return BindingBuilder.bind(queue).to(exchange).with(RabbitMqConstants.TOPIC_EQtoMES_ROUTINGKEY).noargs(); +// } +// @Bean +// public Binding bindingEs2(@Qualifier(RabbitMqConstants.EQtoMES_REPLY_QUEUE) Queue queue, +// @Qualifier(RabbitMqConstants.EXCHANGE_EQtoMES) Exchange exchange) { +// return BindingBuilder.bind(queue).to(exchange).with(RabbitMqConstants.TOPIC_EQtoMES_REPLY_ROUTINGKEY).noargs(); +// } +// +///** +// * TEST2_QUEUE队列绑定交换机,指定routingKey*/ +// +// +// @Bean +// public Binding bindingGitalk(@Qualifier(RabbitMqConstants.MEStoEQ_QUEUE) Queue queue, +// @Qualifier(RabbitMqConstants.EXCHANGE_MEStoEQ) Exchange exchange) { +// return BindingBuilder.bind(queue).to(exchange).with(RabbitMqConstants.TOPIC_MEStoEQ_ROUTINGKEY).noargs(); +// } +// +// @Bean +// public Binding bindingGitalk2(@Qualifier(RabbitMqConstants.MEStoEQ_REPLY_QUEUE) Queue queue, +// @Qualifier(RabbitMqConstants.EXCHANGE_MEStoEQ) Exchange exchange) { +// return BindingBuilder.bind(queue).to(exchange).with(RabbitMqConstants.TOPIC_MEStoEQ_REPLY_ROUTINGKEY).noargs(); +// } +// +// +// +///** +// * 如果需要在生产者需要消息发送后的回调, +// * 需要对rabbitTemplate设置ConfirmCallback对象, +// * 由于不同的生产者需要对应不同的ConfirmCallback, +// * 如果rabbitTemplate设置为单例bean, +// * 则所有的rabbitTemplate实际的ConfirmCallback为最后一次申明的ConfirmCallback。 +// * @return*/ +// +// +// +// @Bean +// @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +// public RabbitTemplate rabbitTemplate() { +// RabbitTemplate template = new RabbitTemplate(connectionFactory); +// return template; +// } + +} diff --git a/zi-wms-pda/src/main/java/com/cim/idm/constants/RabbitMqConstants.java b/zi-wms-pda/src/main/java/com/cim/idm/constants/RabbitMqConstants.java new file mode 100644 index 0000000..e607215 --- /dev/null +++ b/zi-wms-pda/src/main/java/com/cim/idm/constants/RabbitMqConstants.java @@ -0,0 +1,31 @@ +package com.cim.idm.constants; + +/** + * @Description: + * @param + * @Return: + * @Author: Zgg + * @Date: 2024/4/13 10:39 + */ +public interface RabbitMqConstants { + + //EQtoMES + public static final String EXCHANGE_EQtoMES = "SDK.MES.DEV.FAB.EgatetoMES.EXC"; + public static final String TOPIC_EQtoMES_REPLY_ROUTINGKEY = "SDK.MES.DEV.FAB.EgateReplytoMES.KEY"; + public static final String EQtoMES_REPLY_QUEUE = "SDK.MES.DEV.FAB.EgateReplytoMES.QUE"; + public static final String TOPIC_EQtoMES_ROUTINGKEY = "SDK.MES.DEV.FAB.EgatetoMES.KEY"; + public static final String EQtoMES_QUEUE = "SDK.MES.DEV.FAB.EgatetoMES.QUE"; + + + //MEStoEQ + public static final String EXCHANGE_MEStoEQ = "SDK.MES.DEV.FAB.MEStoEgate.EXC"; + + public static final String TOPIC_MEStoEQ_REPLY_ROUTINGKEY = "SDK.MES.DEV.FAB.MESReplytoEgate.KEY"; + + public static final String MEStoEQ_REPLY_QUEUE = "SDK.MES.DEV.FAB.MESReplytoEgate.QUE"; + + public static final String TOPIC_MEStoEQ_ROUTINGKEY = "SDK.MES.DEV.FAB.MEStoEgate.KEY"; + + public static final String MEStoEQ_QUEUE = "SDK.MES.DEV.FAB.MEStoEgate.QUE"; + +} \ No newline at end of file diff --git a/zi-wms-pda/src/main/java/com/cim/idm/controller/LabelController.java b/zi-wms-pda/src/main/java/com/cim/idm/controller/LabelController.java index fc9c725..77a553a 100644 --- a/zi-wms-pda/src/main/java/com/cim/idm/controller/LabelController.java +++ b/zi-wms-pda/src/main/java/com/cim/idm/controller/LabelController.java @@ -547,4 +547,34 @@ public class LabelController { List> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlString, hashMap); return AjaxResult.me().setResultObj(list); } + /* + * 新料号标签打印 + * Existing Stock Label + */ + @RequestMapping(value = "/newMaterialSpecLabelPrint", method = RequestMethod.POST) + //@Operation(summary = "标签打印测试, 测试只能打印 标签模板没有参数的标签. ") + public AjaxResult NewMaterialSpecLabelPrint(@RequestBody JSONObject in) throws CustomException { + try { + String user = in.get("USER").toString(); + String PRINTNAME = in.get("PRINTNAME").toString(); + String LABELCODE = in.get("LABELCODE").toString(); + List> js = (List) in.get("LIST"); + List urlList = new ArrayList<>(); + for (int i = 0; i < js.size(); i++) { + Map jb = js.get(i); + LabelPrintDto1 labelPrintDto = new LabelPrintDto1(); + labelPrintDto.setLotName(jb.get("MATERIALPACKINGNAME").toString()); + labelPrintDto.setDESC_CN(jb.get("DESC_CN").toString()); + labelPrintDto.setOpreater(user); + labelPrintDto.setPrinterName(PRINTNAME); + labelPrintDto.setLabelType(LABELCODE); + String urlInfo = labelService.newMaterialSpecLabelPrint(labelPrintDto); + urlList.add(urlInfo); + } + } catch (Exception e) { + e.printStackTrace(); + return AjaxResult.me().setErrorCode(400).setMessage(e.toString()).setSuccess(false); + } + return AjaxResult.me().setErrorCode(200).setSuccess(true); + } } \ No newline at end of file diff --git a/zi-wms-pda/src/main/java/com/cim/idm/model/LabelPrintPET.java b/zi-wms-pda/src/main/java/com/cim/idm/model/LabelPrintPET.java new file mode 100644 index 0000000..efba962 --- /dev/null +++ b/zi-wms-pda/src/main/java/com/cim/idm/model/LabelPrintPET.java @@ -0,0 +1,44 @@ +package com.cim.idm.model; + +import lombok.Data; + +@Data +public class LabelPrintPET { + /******************************PET标签字段**************************/ + //批次号/SN序号 + private String lotName; + //订单号 + private String productRequestName; + //管芯/钢芯/载具 + private String carrierName; + //品名 + private String productName; + //生产线速 + private String lineSpeed; + //长度 + private String length; + //起始时间(PET主线) + private String startTime; + //下卷时间(PET主线) + private String endTime; + //宽度 + private String wide; + //平均厚度 + private String thickness; + //等级 + private String lotGrade; + //规格/实际规格 + private String practicalSpec; + //母卷批号 + private String parentLotName; + //接头 + private String joint; + //料号 + private String productSpecName; + //净重 + private String weight; + //电晕 + private String corona; + //生产日期 + private String productDate; +} diff --git a/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/BSLabelServiceImpl.java b/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/BSLabelServiceImpl.java index a2281e7..ff07498 100644 --- a/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/BSLabelServiceImpl.java +++ b/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/BSLabelServiceImpl.java @@ -1,6 +1,7 @@ package com.cim.idm.service.Impl; import cn.hutool.core.text.CharSequenceUtil; +import com.alibaba.fastjson.JSONObject; import com.cim.idm.constants.CustomExceptionCode; import com.cim.idm.constants.MsgConstants; import com.cim.idm.constants.PolicyDef; @@ -15,6 +16,7 @@ import com.cim.idm.model.*; import com.cim.idm.model.bo.StorageObject; import com.cim.idm.model.dto.StoragePrintDto; import com.cim.idm.mwmsextend.generic.util.CommonUtil; +import com.cim.idm.service.RabbitMqService; import com.cim.idm.wmsextend.generic.errorHandler.CustomException; import com.cim.idm.wmsextend.generic.util.ObjectUtil; import com.cim.idm.wmspackage.storage.StorageServiceProxy; @@ -29,6 +31,7 @@ import org.apache.commons.logging.LogFactory; import org.jdom.Document; import org.jdom.Element; import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -36,10 +39,17 @@ import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; +import javax.annotation.Resource; import java.lang.reflect.Field; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.*; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; @Service @Slf4j public class BSLabelServiceImpl extends CommonServiceDAO implements ApplicationContextAware { @@ -48,10 +58,11 @@ public class BSLabelServiceImpl extends CommonServiceDAO im private BSLabelHistoryServiceImpl historyService; private BSLabelHistoryDataAdaptor historyDataAdaptor; - + private static final RestTemplate restTemplate = new RestTemplateBuilder().build(); private static Log log = LogFactory.getLog(BSLabelServiceImpl.class); - + @Resource + private RabbitMqService rabbitMqService; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; @@ -1799,6 +1810,432 @@ public class BSLabelServiceImpl extends CommonServiceDAO im // TODO Auto-generated method stub return 0; } - - + + /** + * 新料号标签打印 + * @param MaterialPackingName BOXID + * @param UserId 用户 + * @param printName 打印机 + * @param DESC_CN + * @param labelType 标签模板 + * @return + * @throws IllegalArgumentException + * @throws IllegalAccessException + * @throws JsonProcessingException + * @throws CustomException + */ + public String newMaterialSpecLabel(String MaterialPackingName,String UserId,String printName,String DESC_CN,String labelType) throws IllegalArgumentException, IllegalAccessException, JsonProcessingException, CustomException { + String qeuryLabelDatasql = ""; + String labelAddress = labelType; + String MATERIALPACKINGNAME = MaterialPackingName; + String printer = printName == null || "".equals(printName) ? getDefaultPrinter() : printName;// "\\\\ZXYNB10810864P.boe.com.cn\\TSC MA3400P"; + String server = "LabelRequestURL"; + String requestUrl = getRequestUrlByServer(server); + requestUrl = "0980b551-20a2-49ba-a1e8-950331ff9827"; + List params = getLabelAssignParameter("testLabel002"); + String labelUrl = ""; + String labelPath = getLabelAbsolutePath(labelAddress); + labelPath = "C:\\inetpub\\wwwroot\\BarTender\\wwwroot\\Templates\\WMS\\" + labelAddress; + log.info("***************************PrintLabel Path is : " + labelPath); + PrintRequest pr = new PrintRequest(); + pr.setLibraryID(UUID.randomUUID().toString()); + pr.setAbsolutePath(labelPath); + pr.setCopies(1); + pr.setSerialNumbers(0); + pr.setStartingPosition(0); + pr.setPrinter(printer); + pr.setPrintRequestID(UUID.randomUUID().toString()); + LabelParameterObject obj = new LabelParameterObject(); + List> queryForListProduct = new ArrayList<>(); + if ("PET_A.btw".equals(labelAddress)) { + params = getLabelAssignParameter("labelPET"); + qeuryLabelDatasql = " SELECT\n" + + " LN.BATCH,\n" + + "LN.SOURCEORDER,\n" + + "LN.MATERIALNAME,\n" + + "LN.DEFINEITEM15,\n" + + "LN.DEFINEITEM17,\n" + + "LN.PRACTICALSPEC,\n" + + "LN.JUMBOROLLBATCH,\n" + + "LN.DEFINEITEM18,\n" + + "LN.MATERIALCODE,\n" + + "LN.MAINQTY,\n" + + "LN.DEFINEITEM19,\n" + + "LN.PRODUCTDATE,\n" + + "LN.BARCODE,\n" + + "LN.STAGECODE,\n" + + "LN.DEFINEITEM16,\n" + + "LN.MAINUOM,\n" + + "LN.DEFINEITEM9 " + + "FROM\n" + + "\tLABELPRINTINFO LN \n" + + "WHERE\n" + + "\tLN.BARCODE =:MATERIALPACKINGNAME "; + Map qeuryLabelMap = new HashMap(); + qeuryLabelMap.put("MATERIALPACKINGNAME", MATERIALPACKINGNAME); + queryForListProduct = IDMFrameServiceProxy.getSqlTemplate().queryForList(qeuryLabelDatasql, qeuryLabelMap); + if (queryForListProduct != null && queryForListProduct.size() > 0) { + + LabelPrintPET labelPrintPET = new LabelPrintPET(); + //SN序号 + labelPrintPET.setLotName(queryForListProduct.get(0).get("BARCODE") == null ? "" : queryForListProduct.get(0).get("BARCODE").toString()); + //订单号 + labelPrintPET.setProductRequestName(queryForListProduct.get(0).get("SOURCEORDER") == null ? "" : queryForListProduct.get(0).get("SOURCEORDER").toString()); + labelPrintPET.setCarrierName(queryForListProduct.get(0).get("stageCode") == null ? "" : queryForListProduct.get(0).get("stageCode").toString()); + //品名 + labelPrintPET.setProductName(queryForListProduct.get(0).get("MATERIALNAME") == null ? "" : queryForListProduct.get(0).get("MATERIALNAME").toString()); + //等级 + labelPrintPET.setLotGrade(queryForListProduct.get(0).get("DEFINEITEM17") == null ? "" : queryForListProduct.get(0).get("DEFINEITEM17").toString()); + //规格 + String practicakSpes = queryForListProduct.get(0).get("PRACTICALSPEC") == null ? "" : queryForListProduct.get(0).get("PRACTICALSPEC").toString(); + //厚度 + String defineItem15 = queryForListProduct.get(0).get("DEFINEITEM15") == null ? "" : queryForListProduct.get(0).get("DEFINEITEM15").toString(); + //规格=厚度+微米+规格 + labelPrintPET.setPracticalSpec(defineItem15 + "µm" + practicakSpes); + //母卷批号 + labelPrintPET.setParentLotName(queryForListProduct.get(0).get("JUMBOROLLBATCH") == null ? "" : queryForListProduct.get(0).get("JUMBOROLLBATCH").toString()); + //接头 + labelPrintPET.setJoint(queryForListProduct.get(0).get("DEFINEITEM18") == null ? "" : queryForListProduct.get(0).get("DEFINEITEM18").toString()); + //料号 + String materialCode = queryForListProduct.get(0).get("MATERIALCODE") == null ? "" : queryForListProduct.get(0).get("MATERIALCODE").toString(); + //阶段 + String stageCode = queryForListProduct.get(0).get("STAGECODE") == null ? "" : queryForListProduct.get(0).get("STAGECODE").toString(); + labelPrintPET.setProductSpecName(materialCode + stageCode); + //净重 + labelPrintPET.setWeight(queryForListProduct.get(0).get("MAINQTY") == null ? "" : queryForListProduct.get(0).get("MAINQTY").toString()); + //电晕 + labelPrintPET.setCorona(queryForListProduct.get(0).get("DEFINEITEM19") == null ? "" : queryForListProduct.get(0).get("DEFINEITEM19").toString()); + //分切日期 + labelPrintPET.setProductDate(queryForListProduct.get(0).get("PRODUCTDATE") == null ? "" : queryForListProduct.get(0).get("PRODUCTDATE").toString()); + //型号 + String defineitem16 = queryForListProduct.get(0).get("DEFINEITEM16") == null ? "" : queryForListProduct.get(0).get("DEFINEITEM16").toString(); + //检验员 + String defineitem9 = queryForListProduct.get(0).get("DEFINEITEM9") == null ? "" : queryForListProduct.get(0).get("DEFINEITEM9").toString(); + labelPrintPET.setWide(""); + labelPrintPET.setThickness(""); + labelPrintPET.setLength(""); + labelPrintPET.setLineSpeed(""); + labelPrintPET.setStartTime(""); + labelPrintPET.setEndTime(""); + log.info("***************************PrintLabel Assign params is : " + params.toString()); + labelUrl = labelPrintRabbitMQ(labelPrintPET, requestUrl, pr, params); + log.info("***************************PrintLabel Use URL is : " + requestUrl); + }else { + throw new CustomException(CustomExceptionCode.DATA_NOT_FOUND,"Undefined Execute Type : "); + } + + }else if ("Sdk2.btw".equals(labelAddress)){ + qeuryLabelDatasql = "SELECT\r\n" + + " m.MATERIALPACKINGNAME barcode,m2.materialtype,\r\n" + + " m.MATERIALSPECNAME partNo,\r\n" + + " m.PHASE state,\r\n" + + " ss.SPECNAME sdkSpec,\r\n" + + " m2.DESC_CN partName,m2.description,\r\n" + + " m.TRUEGG PracticalSpec,\r\n" + + " DECODE(SUBSTR(m.MATERIALQUANTITY,1,1),'.','0'||m.MATERIALQUANTITY,m.MATERIALQUANTITY) || ' ' || m3.FNAME qty,\r\n" + + " m.RECEIVEREQUESTNAME orderNo,\r\n" + + " m.RECEIVEUSER operater,\r\n" + + " m.CHARGE lotNo,NVL(m.suppliername,'') supplierNo,\r\n" + + " m.REMARK remark,TO_CHAR(m.RECEIVETIME,'YYYYMMDD') jumboRollBatch," + + "TO_CHAR(MAKEDATE,'YYYYMMDD') makedate, TO_CHAR(EXPIRINGDATE,'YYYYMMDD') expdate ,m.RECEIVEUSER opreater\r\n" + + "FROM\r\n" + + " MATERIALPACKING m\r\n" + + "LEFT JOIN SDK_SPEC ss ON\r\n" + + " m.SDK_ID = ss.SDK_ID\r\n" + + "LEFT JOIN MATERIALSPEC m2 ON\r\n" + + " m.MATERIALSPECNAME = m2.MATERIALSPECNAME\r\n" + + "LEFT JOIN MATERIALUNIT m3 ON\r\n" + + " m.UNIT = m3.FNUMBER\r\n" + + "WHERE\r\n" + + " m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME"; + Map qeuryLabelMap = new HashMap(); + qeuryLabelMap.put("MATERIALPACKINGNAME", MATERIALPACKINGNAME); + queryForListProduct = IDMFrameServiceProxy.getSqlTemplate().queryForList(qeuryLabelDatasql, qeuryLabelMap); + obj.setBarcode(queryForListProduct.get(0).get("barcode") != null ? queryForListProduct.get(0).get("barcode").toString() : ""); + obj.setMakedate(queryForListProduct.get(0).get("makedate") != null ? queryForListProduct.get(0).get("makedate").toString() : ""); + obj.setExpdate(queryForListProduct.get(0).get("expdate") != null ? queryForListProduct.get(0).get("expdate").toString() : ""); + obj.setDescription(queryForListProduct.get(0).get("description") != null ? queryForListProduct.get(0).get("description").toString() : ""); +// private String partNo; + obj.setPartNo(queryForListProduct.get(0).get("partNo") != null ? queryForListProduct.get(0).get("partNo").toString() : ""); +// private String state; + obj.setState(queryForListProduct.get(0).get("state") != null ? queryForListProduct.get(0).get("state").toString() : ""); +// private String sdkSpec; + obj.setSdkSpec(queryForListProduct.get(0).get("sdkSpec") != null ? queryForListProduct.get(0).get("sdkSpec").toString() : ""); +// private String partName; +// obj.setPartName(queryForList.get(0).get("partName") != null ? queryForList.get(0).get("partName").toString() : ""); + if (!"".equals(DESC_CN) && DESC_CN != "") { + obj.setPartName(DESC_CN); + } else { + obj.setPartName(queryForListProduct.get(0).get("partName") != null ? queryForListProduct.get(0).get("partName").toString() : ""); + } + //private String ParticalSpec; + obj.setPracticalSpec(queryForListProduct.get(0).get("PracticalSpec") != null ? queryForListProduct.get(0).get("PracticalSpec").toString() : ""); +// private String qty; + obj.setQty(queryForListProduct.get(0).get("qty") != null ? queryForListProduct.get(0).get("qty").toString() : ""); +// private String orderNo; + obj.setOrderNo(queryForListProduct.get(0).get("orderNo") != null ? queryForListProduct.get(0).get("orderNo").toString() : ""); + obj.setSourceOrder(queryForListProduct.get(0).get("sourceOrder") != null ? queryForListProduct.get(0).get("sourceOrder").toString() : ""); + obj.setPiece(queryForListProduct.get(0).get("piece") != null ? queryForListProduct.get(0).get("piece").toString() : ""); + obj.setOperater(queryForListProduct.get(0).get("operater") != null ? queryForListProduct.get(0).get("operater").toString() : ""); +// private String operater; +// obj.setOpreater(queryForList.get(0).get("operater") != null ? queryForList.get(0).get("operater").toString() : ""); + obj.setJumboRollBatch(queryForListProduct.get(0).get("jumboRollBatch") != null ? queryForListProduct.get(0).get("jumboRollBatch").toString() : ""); + obj.setSpecifications(queryForListProduct.get(0).get("specifications") != null ? queryForListProduct.get(0).get("specifications").toString() : ""); + obj.setPracticalSpec(queryForListProduct.get(0).get("PracticalSpec") != null ? queryForListProduct.get(0).get("PracticalSpec").toString() : ""); + obj.setCustomNo(queryForListProduct.get(0).get("customNo") != null ? queryForListProduct.get(0).get("customNo").toString() : ""); + // obj.setOpreater(UserId); +// private String lotNo; + obj.setLotNo(queryForListProduct.get(0).get("lotNo") != null ? queryForListProduct.get(0).get("lotNo").toString() : ""); +// private String remark; + obj.setRemark(queryForListProduct.get(0).get("remark") != null ? queryForListProduct.get(0).get("remark").toString() : ""); + obj.setRemarks(queryForListProduct.get(0).get("remarks") != null ? queryForListProduct.get(0).get("remarks").toString() : ""); +// obj.setJumboRollBatch(queryForList.get(0).get("jumboRollBatch") != null ? queryForList.get(0).get("jumboRollBatch").toString() : ""); + obj.setMakedate(queryForListProduct.get(0).get("makedate") != null ? queryForListProduct.get(0).get("makedate").toString() : ""); + obj.setSupplierno(queryForListProduct.get(0).get("supplierNo") != null ? queryForListProduct.get(0).get("supplierNo").toString() : ""); + obj.setDescription(queryForListProduct.get(0).get("description") != null ? queryForListProduct.get(0).get("description").toString() : ""); + log.info("***************************PrintLabel Assign params is : " + params.toString()); + labelUrl = labelPrintRabbitMQ(obj, requestUrl, pr, params); + log.info("***************************PrintLabel Use URL is : " + requestUrl); + }else if ("胶水原材.btw".equals(labelAddress)){ + qeuryLabelDatasql = "SELECT\r\n" + + " m.MATERIALPACKINGNAME barcode,m2.materialtype,\r\n" + + " m.MATERIALSPECNAME partNo,\r\n" + + " m.PHASE state,\r\n" + + " ss.SPECNAME sdkSpec,\r\n" + + " m2.DESC_CN partName,m2.description,\r\n" + + " m.TRUEGG PracticalSpec,\r\n" + + " DECODE(SUBSTR(m.MATERIALQUANTITY,1,1),'.','0'||m.MATERIALQUANTITY,m.MATERIALQUANTITY) || ' ' || m3.FNAME qty,\r\n" + + " m.RECEIVEREQUESTNAME orderNo,\r\n" + + " m.RECEIVEUSER operater,\r\n" + + " m.CHARGE lotNo,NVL(m.suppliername,'') supplierNo,\r\n" + + " m.REMARK remark,TO_CHAR(m.RECEIVETIME,'YYYYMMDD') jumboRollBatch," + + "TO_CHAR(MAKEDATE,'YYYYMMDD') makedate, TO_CHAR(EXPIRINGDATE,'YYYYMMDD') expdate ,m.RECEIVEUSER opreater\r\n" + + "FROM\r\n" + + " MATERIALPACKING m\r\n" + + "LEFT JOIN SDK_SPEC ss ON\r\n" + + " m.SDK_ID = ss.SDK_ID\r\n" + + "LEFT JOIN MATERIALSPEC m2 ON\r\n" + + " m.MATERIALSPECNAME = m2.MATERIALSPECNAME\r\n" + + "LEFT JOIN MATERIALUNIT m3 ON\r\n" + + " m.UNIT = m3.FNUMBER\r\n" + + "WHERE\r\n" + + " m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME"; + Map qeuryLabelMap = new HashMap(); + qeuryLabelMap.put("MATERIALPACKINGNAME", MATERIALPACKINGNAME); + queryForListProduct = IDMFrameServiceProxy.getSqlTemplate().queryForList(qeuryLabelDatasql, qeuryLabelMap); + obj.setBarcode(queryForListProduct.get(0).get("barcode") != null ? queryForListProduct.get(0).get("barcode").toString() : ""); + obj.setMakedate(queryForListProduct.get(0).get("makedate") != null ? queryForListProduct.get(0).get("makedate").toString() : ""); + obj.setExpdate(queryForListProduct.get(0).get("expdate") != null ? queryForListProduct.get(0).get("expdate").toString() : ""); + obj.setDescription(queryForListProduct.get(0).get("description") != null ? queryForListProduct.get(0).get("description").toString() : ""); +// private String partNo; + obj.setPartNo(queryForListProduct.get(0).get("partNo") != null ? queryForListProduct.get(0).get("partNo").toString() : ""); +// private String state; + obj.setState(queryForListProduct.get(0).get("state") != null ? queryForListProduct.get(0).get("state").toString() : ""); +// private String sdkSpec; + obj.setSdkSpec(queryForListProduct.get(0).get("sdkSpec") != null ? queryForListProduct.get(0).get("sdkSpec").toString() : ""); +// private String partName; +// obj.setPartName(queryForList.get(0).get("partName") != null ? queryForList.get(0).get("partName").toString() : ""); + if (!"".equals(DESC_CN) && DESC_CN != "") { + obj.setPartName(DESC_CN); + } else { + obj.setPartName(queryForListProduct.get(0).get("partName") != null ? queryForListProduct.get(0).get("partName").toString() : ""); + } + //private String ParticalSpec; + obj.setPracticalSpec(queryForListProduct.get(0).get("PracticalSpec") != null ? queryForListProduct.get(0).get("PracticalSpec").toString() : ""); +// private String qty; + obj.setQty(queryForListProduct.get(0).get("qty") != null ? queryForListProduct.get(0).get("qty").toString() : ""); +// private String orderNo; + obj.setOrderNo(queryForListProduct.get(0).get("orderNo") != null ? queryForListProduct.get(0).get("orderNo").toString() : ""); + obj.setSourceOrder(queryForListProduct.get(0).get("sourceOrder") != null ? queryForListProduct.get(0).get("sourceOrder").toString() : ""); + obj.setPiece(queryForListProduct.get(0).get("piece") != null ? queryForListProduct.get(0).get("piece").toString() : ""); + obj.setOperater(queryForListProduct.get(0).get("operater") != null ? queryForListProduct.get(0).get("operater").toString() : ""); +// private String operater; +// obj.setOpreater(queryForList.get(0).get("operater") != null ? queryForList.get(0).get("operater").toString() : ""); + obj.setJumboRollBatch(queryForListProduct.get(0).get("jumboRollBatch") != null ? queryForListProduct.get(0).get("jumboRollBatch").toString() : ""); + obj.setSpecifications(queryForListProduct.get(0).get("specifications") != null ? queryForListProduct.get(0).get("specifications").toString() : ""); + obj.setPracticalSpec(queryForListProduct.get(0).get("PracticalSpec") != null ? queryForListProduct.get(0).get("PracticalSpec").toString() : ""); + obj.setCustomNo(queryForListProduct.get(0).get("customNo") != null ? queryForListProduct.get(0).get("customNo").toString() : ""); + // obj.setOpreater(UserId); +// private String lotNo; + obj.setLotNo(queryForListProduct.get(0).get("lotNo") != null ? queryForListProduct.get(0).get("lotNo").toString() : ""); +// private String remark; + obj.setRemark(queryForListProduct.get(0).get("remark") != null ? queryForListProduct.get(0).get("remark").toString() : ""); + obj.setRemarks(queryForListProduct.get(0).get("remarks") != null ? queryForListProduct.get(0).get("remarks").toString() : ""); +// obj.setJumboRollBatch(queryForList.get(0).get("jumboRollBatch") != null ? queryForList.get(0).get("jumboRollBatch").toString() : ""); + obj.setMakedate(queryForListProduct.get(0).get("makedate") != null ? queryForListProduct.get(0).get("makedate").toString() : ""); + obj.setSupplierno(queryForListProduct.get(0).get("supplierNo") != null ? queryForListProduct.get(0).get("supplierNo").toString() : ""); + obj.setDescription(queryForListProduct.get(0).get("description") != null ? queryForListProduct.get(0).get("description").toString() : ""); + log.info("***************************PrintLabel Assign params is : " + params.toString()); + labelUrl = labelPrintRabbitMQ(obj, requestUrl, pr, params); + log.info("***************************PrintLabel Use URL is : " + requestUrl); + }else { + throw new CustomException(CustomExceptionCode.DATA_NOT_FOUND, "未找到对应的标签模板"); + } + return labelUrl; + + } + + /** + * 连接sqlserver获取打印数据 + * @param sqlStr SQL字符串 + */ + public void queryDataFromSqlServer(String sqlStr) { + String url = "jdbc:sqlserver://192.168.1.35:1433;databaseName=Kgm_SdkNcDb;encrypt=true;trustServerCertificate=true;"; + String user = "kgm"; + String password = "kgm123!@#"; + try (Connection conn = DriverManager.getConnection(url, user, password); + PreparedStatement stmt = conn.prepareStatement(sqlStr)) { + stmt.setString(1, "someValue"); // 设置参数 + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + // 处理结果集 + System.out.println("ID: " + rs.getInt("ID") + ", Name: " + rs.getString("Name")); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + /** + * + * This function is labelPrint + * @param data --any data + * @param requestURL + * @param printRequest + * @param nameParams -- labelAssign parameter + * @throws CustomException + * @throws IllegalArgumentException + * @throws IllegalAccessException + * @throws JsonProcessingException + * @author ZXY Team. + * @date 2022年5月6日 + */ + public String labelPrintRabbitMQ(Object data, String requestURL, PrintRequest printRequest,List nameParams) throws CustomException + { + if (data != null && nameParams.size() > 0) { + Map namedDataSources = new HashMap(); + Field[] fields = data.getClass().getDeclaredFields(); + for (String key : nameParams) { + namedDataSources.put(key, StringUtils.EMPTY); + for (Field field : fields) { + if (field.getName().equals("key")) { + KeyInfo sourceKey = ObjectUtil.getKeyInfo(data); + Field[] keyFields = sourceKey.getClass().getDeclaredFields(); + boolean isPut = false; + for (Field keyField : keyFields) { + if (key.toUpperCase().equals(keyField.getName().toUpperCase())) { + keyField.setAccessible(true); + try { + namedDataSources.put(key, String.valueOf(keyField.get(sourceKey))); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + isPut = true; + break; + } + } + if (isPut) break; + } + if (key.toUpperCase().equals(field.getName().toUpperCase())) { + field.setAccessible(true); + + if("CREATETIME".equals(field.getName().toUpperCase())) { + Timestamp time = null; + try { + time = (Timestamp) field.get(data); + } + catch (Exception e) { + try { + namedDataSources.put(key, String.valueOf(field.get(data))); + } catch (IllegalArgumentException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IllegalAccessException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + break; + } + String timeKey = new SimpleDateFormat("yyyy/MM/dd*HH:mm:SS").format(time); + namedDataSources.put(key, timeKey); + break; + } + + try { + namedDataSources.put(key, String.valueOf(field.get(data))); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + break; + } + } + } + printRequest.setNamedDataSources(namedDataSources); + Map dataEntryControls = new HashMap<>(); + printRequest.setDataEntryControls(dataEntryControls ); + } + + ObjectMapper objectMapper = new ObjectMapper(); + String labelRequestParameter = ""; + try { + labelRequestParameter = objectMapper.writeValueAsString(printRequest); + } catch (JsonProcessingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + log.info("---------------------------labelRequestParameter---------------------------------"); + log.info(labelRequestParameter); + String bodyinfo = ""; + try { + //35 服务器装了 bartender服务: + //1.可以连接打印机,把本地btw文件发给斑马打印机; + //2.可以给文件绑定key-value,给模板传值; + //3.暴露接口: 服务地址、打印文件地址、打印文件里面key-value绑定对象、打印机名称。 + //流程:1.通过服务地址找到文件模板, 解析模板,模板里面绑定key,通过 绑定对象把value传给key(相当于替换模板内容); + //2.通过我们传过去的打印机名称,去找打印机IP,下发打印任务。 + //重点关注:1.服务地址,2.模板的具名数据源(KEY),3.key-value绑定对象(>=key,名称一样),4.打印机名称,5.模板路径 +// PrintSuccess result = + //PrintSuccess forObject = restTemplate.getForObject(requestURL, PrintSuccess.class, printRequest); +// HttpEntity requestEntity = new HttpEntity<>(JSONObject.toJSONString(data), BSLabelServiceImpl.getRequestHeaders()); + // 返回值为BaseEntity实体类,只有一个字段时不用配置请求头也能正常解析,但存在两个字段及以上时会出现415异常(问题未知,有人知道求告知) + + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity<>(printRequest, headers); + // 1.获取开始时间 + long startTime = System.currentTimeMillis(); + //ResponseEntity response = restTemplate.exchange(requestURL, HttpMethod.POST, entity, String.class); + //通过固定的routingKey将标签打印的数据发送到MQ + rabbitMqService.sendMesToClient(JSONObject.toJSONString(printRequest),printRequest.getPrinter()); + long endTime = System.currentTimeMillis(); //获取结束时间 + String conTime = "程序运行时间:" + (endTime - startTime) + "ms"; + log.info("标签打印-批次号:" + printRequest.getNamedDataSources().get("batch") + "的打印时间为" + + conTime +"毫秒"); //输出程序运行时间 +// log.info("标签打印:"+response.getBody()); + //bodyinfo = response.getBody(); + +// HttpHeaders headers = new HttpHeaders(); +// headers.setContentType(MediaType.APPLICATION_JSON); +// HttpEntity httpEntity = new HttpEntity<>(printRequest, headers); +// new RestTemplateBuilder().build().exchange(requestURL, "POST", httpEntity, String.class); +// PrintSuccess postForObject = new RestTemplateBuilder().build().postForObject(requestURL, httpEntity, PrintSuccess.class, printRequest); +// //PrintSuccess postForObject = new RestTemplateBuilder().build().postForObject(requestURL, printRequest, PrintSuccess.class);//requestURL(1)printRequest(2~5) + + } catch (Exception e) { + e.printStackTrace(); + throw new CustomException(e.getMessage().toString()); + } + + return bodyinfo; + + } } diff --git a/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/LabelServiceImpl.java b/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/LabelServiceImpl.java index 5d79165..411ac92 100644 --- a/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/LabelServiceImpl.java +++ b/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/LabelServiceImpl.java @@ -333,4 +333,15 @@ public class LabelServiceImpl implements LabelService { e.printStackTrace(); } } + @Override + public String newMaterialSpecLabelPrint(LabelPrintDto1 data) throws CustomException { + String urlFull = ""; + try { + urlFull = bsLabelService.newMaterialSpecLabel(data.getLotName(),data.getOpreater(),data.getPrinterName(),data.getDESC_CN(),data.getLabelType()); + } catch (Exception e) { + e.printStackTrace(); + throw new CustomException( "标签打印异常... " + e.getMessage()); + } + return urlFull; + } } diff --git a/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/RabbitMqServiceNewImpl.java b/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/RabbitMqServiceNewImpl.java new file mode 100644 index 0000000..7091bda --- /dev/null +++ b/zi-wms-pda/src/main/java/com/cim/idm/service/Impl/RabbitMqServiceNewImpl.java @@ -0,0 +1,45 @@ +package com.cim.idm.service.Impl; + + +import com.cim.idm.constants.RabbitMqConstants; +import com.cim.idm.service.RabbitMqService; +import com.cim.idm.utils.RabbitMqUtilsNew; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * @param + * @Description: + * @Return: + * @Author: Zgg + * @Date: 2024/4/13 10:53*/ + + +@Service +public class RabbitMqServiceNewImpl implements RabbitMqService { + + @Autowired + private RabbitMqUtilsNew rabbitMqUtils; + +// @Override +// public void sendMesToEq(String content) { +// rabbitMqUtils.sendByRoutingKey(RabbitMqConstants.EXCHANGE_MEStoEQ, +// RabbitMqConstants.TOPIC_MEStoEQ_ROUTINGKEY, content); +// } + + @Override + public void sendMesToEq(String content) { + rabbitMqUtils.sendByRoutingKey("SDK.MES.CLINET.3.3.170.248.EXC", "SDK.MES.CLINET.3.3.170.248.KEY", content); + } + + @Override + public void sendMesToClient(String content,String routingKey) { + rabbitMqUtils.sendByRoutingKey("", routingKey, content); + } + + @Override + public void sendMesToEqReply(String content, String correlationId) { + rabbitMqUtils.sendReplyByRoutingKey(RabbitMqConstants.EXCHANGE_MEStoEQ, + RabbitMqConstants.TOPIC_MEStoEQ_REPLY_ROUTINGKEY, content, correlationId); + } +} diff --git a/zi-wms-pda/src/main/java/com/cim/idm/service/LabelService.java b/zi-wms-pda/src/main/java/com/cim/idm/service/LabelService.java index 590aaac..6feab3b 100644 --- a/zi-wms-pda/src/main/java/com/cim/idm/service/LabelService.java +++ b/zi-wms-pda/src/main/java/com/cim/idm/service/LabelService.java @@ -122,5 +122,8 @@ public interface LabelService { */ // void saveNcData(List data) throws IllegalArgumentException; - + /** + * 新料号标签打印 + */ + String newMaterialSpecLabelPrint(LabelPrintDto1 data) throws CustomException; } diff --git a/zi-wms-pda/src/main/java/com/cim/idm/service/RabbitMqService.java b/zi-wms-pda/src/main/java/com/cim/idm/service/RabbitMqService.java new file mode 100644 index 0000000..58472ba --- /dev/null +++ b/zi-wms-pda/src/main/java/com/cim/idm/service/RabbitMqService.java @@ -0,0 +1,22 @@ +package com.cim.idm.service; + +import org.springframework.stereotype.Service; + +/** + * @param + * @Description: + * @Return: + * @Author: Zgg + * @Date: 2024/4/13 10:52*/ + + +@Service +public interface RabbitMqService { + + void sendMesToEq(String content); + + void sendMesToClient(String content,String routingKey); + + void sendMesToEqReply(String content, String correlationId); +} + diff --git a/zi-wms-pda/src/main/java/com/cim/idm/utils/IRequester.java b/zi-wms-pda/src/main/java/com/cim/idm/utils/IRequester.java new file mode 100644 index 0000000..6a8acf4 --- /dev/null +++ b/zi-wms-pda/src/main/java/com/cim/idm/utils/IRequester.java @@ -0,0 +1,20 @@ +package com.cim.idm.utils; + + + +public interface IRequester +{ + public void send(Object message); + + public void send(String subjectName, Object message); + + public void reply(String subjectName, Object message); + + public Object sendRequest(Object message); + + public Object sendRequest(Object message, int replyTimeout); + + public Object sendRequest(String subjectName, Object message); + + public Object sendRequest(String subjectName, Object message, long replyTimeout); +} diff --git a/zi-wms-pda/src/main/java/com/cim/idm/utils/RabbitMqUtilsNew.java b/zi-wms-pda/src/main/java/com/cim/idm/utils/RabbitMqUtilsNew.java new file mode 100644 index 0000000..8fc61cb --- /dev/null +++ b/zi-wms-pda/src/main/java/com/cim/idm/utils/RabbitMqUtilsNew.java @@ -0,0 +1,103 @@ +package com.cim.idm.utils; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessageProperties; +import org.springframework.amqp.rabbit.connection.CorrelationData; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +/** + * @Description: + * @param + * @Return: + * @Author: Zgg + * @Date: 2024/4/13 10:46*/ + + +@Slf4j +@Component +public class RabbitMqUtilsNew implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback{ + + private RabbitTemplate rabbitTemplate; + +/** + * 构造方法注入*/ + + + @Autowired + public RabbitMqUtilsNew(RabbitTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; + //这是是设置回调能收到发送到响应 + rabbitTemplate.setConfirmCallback(this); + //如果设置备份队列则不起作用 + rabbitTemplate.setMandatory(true); + rabbitTemplate.setReturnCallback(this); + } + +/** + * 回调确认*/ + + + @Override + public void confirm(CorrelationData correlationData, boolean ack, String cause) { + if(ack){ + log.info("消息发送成功:correlationData({}),ack({}),cause({})",correlationData,ack,cause); + }else{ + log.info("消息发送失败:correlationData({}),ack({}),cause({})",correlationData,ack,cause); + } + } + +/** + * 消息发送到转换器的时候没有对列,配置了备份对列该回调则不生效 + * @param message + * @param replyCode + * @param replyText + * @param exchange + * @param routingKey*/ + + + @Override + public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) { + log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}",exchange,routingKey,replyCode,replyText,message); + } + +/** + * 发送到指定Queue + * @param queueName + * @param obj*/ + + + public void send(String queueName, Object obj){ + CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString()); + this.rabbitTemplate.convertAndSend(queueName, obj, correlationId); + } + +/* +* + * 1、交换机名称 + * 2、routingKey + * 3、消息内容 +*/ + + + public void sendByRoutingKey(String exChange, String routingKey, Object obj){ + CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString()); + this.rabbitTemplate.convertAndSend(exChange, routingKey, obj, correlationId); + } + + public void sendReplyByRoutingKey(String exChange, String routingKey, String obj, String correlationId){ + byte[] body = obj.getBytes(); + MessageProperties messageProperties = new MessageProperties(); + messageProperties.setCorrelationId(correlationId); + // 创建Message对象 + Message message = new Message(body, messageProperties); + // 发送消息 + this.rabbitTemplate.send(exChange, routingKey, message); + /*CorrelationData correlationData = new CorrelationData(correlationId); + this.rabbitTemplate.convertAndSend(exChange, routingKey, obj, correlationData);*/ + } +} diff --git a/zi-wms-pda/src/main/java/com/cim/idm/utils/RabbitRequester.java b/zi-wms-pda/src/main/java/com/cim/idm/utils/RabbitRequester.java new file mode 100644 index 0000000..16b4e0a --- /dev/null +++ b/zi-wms-pda/src/main/java/com/cim/idm/utils/RabbitRequester.java @@ -0,0 +1,267 @@ +package com.cim.idm.utils; + +import com.rabbitmq.client.*; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +public class RabbitRequester implements IRequester { + + private Lock lock = new ReentrantLock(); + private static RabbitRequester rabbitMqRPCClient; + private Log log = LogFactory.getLog(this.getClass()); + private String host; + private String port; + + private int channelNum =0; + private String username; + private String password; + private String virtualHost; + + private String exchange; + private String routingKey; + private long timeOut = 300000; + + private int connectPoolSize = 10; + private int currentConnNum = 0; + private int connectSize =0; + private List connectionList = new LinkedList<>(); + + public String getExchange() { + return exchange; + } + + public void setExchange(String exchange) { + this.exchange = exchange; + } + + public String getRoutingKey() { + return routingKey; + } + + public void setRoutingKey(String routingKey) { + this.routingKey = routingKey; + } + + public int getConnectSize() { + return connectSize; + } + + public void setConnectPoolSize(int connectPoolSize) { + this.connectPoolSize = connectPoolSize; + } + + public void afterPropertiesSet() throws Exception { + for(int i=0; i=connectPoolSize) { + currentConnNum =0; + } + if (connectionList.size() > currentConnNum) { + return connectionList.get(currentConnNum++); + } else { + return connectionList.get(currentConnNum++%connectionList.size()); + } + } + public String call(Connection connection ,String exchange, String routingKey, String message, long timeout) throws IOException, InterruptedException { + lock.lock(); + Channel channel = connection.createChannel(); + lock.unlock(); + try{ + //定义一个临时变量的接受队列名 + String replyQueueName = channel.queueDeclare().getQueue(); + + //生成一个唯一的字符串作为回调队列的编号 + final String corrId = UUID.randomUUID().toString(); + //String basicConsume(String queue, boolean autoAck, Consumer callback) + //发送请求消息,消息使用了两个属性:replyto和correlationId + //服务端根据replyto返回结果,客户端根据correlationId判断响应是不是给自己的 + AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName).build(); + + //发布一个消息,requestQueueName路由规则 + channel.basicPublish(exchange, routingKey, props, message.getBytes("UTF-8")); + + //由于我们的消费者交易处理是在单独的线程中进行的,因此我们需要在响应到达之前暂停主线程。 + //这里我们创建的 容量为1的阻塞队列ArrayBlockingQueue,因为我们只需要等待一个响应。 + final BlockingQueue response = new ArrayBlockingQueue(1); + + channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) { + @Override + public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { + //检查它的correlationId是否是我们所要找的那个 + System.out.println("Connection:" +currentConnNum+",DeliveryTag:"+envelope.getDeliveryTag()); + if (properties.getCorrelationId().equals(corrId)) { + //如果是,则响应BlockingQueue + response.offer(new String(body, "UTF-8")); + } + } + }); + String result = response.poll(timeout, TimeUnit.MILLISECONDS); + return result; + }catch (Exception e){ + System.out.println(e.getMessage()); + }finally { + try { + channel.close(); + } catch (TimeoutException e) { + e.printStackTrace(); + } + } + return null; + } + + public void close(Connection connection) throws IOException { + connectionList.remove(connection); + connection.close(); + } +}