1. 程式人生 > >Java之品優購課程講義_day13(8)

Java之品優購課程講義_day13(8)

商品刪除-刪除商品詳細頁 7.1 需求分析 執行商品刪除後,同時刪除每個伺服器上的商品詳細頁 7.2 訊息生產者(運營商後臺) 7.2.1 配置檔案 修改 spring-activemq.xml,新增配置


<!--這個是訂閱模式 用於刪除頁面-->

<bean  id="topicPageDeleteDestination" class="org.apache.activemq.command.ActiveMQTopic">

<constructor-arg  value="pinyougou_topic_page_delete"/>

</bean>
7.1.1 程式碼實現
修改 GoodsController.java

@Autowired

private  Destination  topicPageDeleteDestination;//用於刪除靜態網頁的訊息

/**

*批量刪除

*@param  ids

*@return

*/
@RequestMapping("/delete")

public  Result  delete(final  Long  []  ids){

try {

goodsService.delete(ids); jmsTemplate.send(queueSolrDeleteDestination,  new  MessageCreator()  {
@Override

public  Message  createMessage(Session  session)  throws  JMSException  {

return  session.createObjectMessage(ids);

}

});

//刪除頁面

jmsTemplate.send(topicPageDeleteDestination,  new  MessageCreator()  { @Override
public  Message  createMessage(Session  session)  throws  JMSException  {

return  session.createObjectMessage(ids);

}

});

return  new  Result(true,  "刪除成功");

}  catch  (Exception  e)  { e.printStackTrace();
return  new  Result(false,  "刪除失敗");

}

}
7.1 訊息消費者(頁面生成服務)7.1.1 配置檔案
修改 pinyougou-page-service 的 applicationContext-activemq-consumer.xml

<!--刪除頁面 -->

<bean  id="topicPageDeleteDestination" class="org.apache.activemq.command.ActiveMQTopic">

<constructor-arg  value="pinyougou_topic_page_delete"/>

</bean>

<!-- 訊息監聽容器 -->

<bean  class="org.springframework.jms.listener.DefaultMessageListenerContainer">

<property  name="connectionFactory"  ref="connectionFactory"  />

<property  name="destination"  ref="topicPageDeleteDestination"  />

<property  name="messageListener"  ref="pageDeleteListener"  />

</bean>
7.1.1 程式碼實現
(1)修改 pinyougou-page-interface 的 ItemPageService.java

/**

*刪除商品詳細頁

*@param  goodsId

*@return

*/

public  boolean  deleteItemHtml(Long[]  goodsIds);
(2)修改 pinyougou-page-service 的 ItemPageServiceImpl.java

@Override

public  boolean  deleteItemHtml(Long[]  goodsIds)  {

try {

for(Long  goodsId:goodsIds){

new  File(pagedir+goodsId+".html").delete();

}

return  true;

}  catch  (Exception  e)  { e.printStackTrace(); return  false;
}

}
(3)建立監聽類 PageDeleteListener

@Component

public  class  PageDeleteListener  implements  MessageListener  {

@Autowired

private  ItemPageService  itemPageService;

@Override

public  void  onMessage(Message  message)  {
ObjectMessage  objectMessage=  (ObjectMessage)message;

try {

Long[]  goodsIds  =  (Long[])  objectMessage.getObject();

System.out.println("ItemDeleteListener 監聽接收到訊息..."+goodsIds);

boolean  b  =  itemPageService.deleteItemHtml(goodsIds);

System.out.println("網頁刪除結果:"+b);

}  catch  (JMSException  e)  { e.printStackTrace();
}

}

}