现在需要通过ActiveMQ消息中间件实现在商品删除时也同时移除索引库记录的功能。
消息生产者(运营商后台)1)修改 pinyougou-manager-web 工程的 spring-activemq.xml,添加 bean 配置
2) 代码实现,修改 GoodsController.java:
@Autowired
private Destination queueSolrDeleteDestination;//用户在索引库中删除记录
/**
* 批量删除
* @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);
}
});
return new Result(true, "删除成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "删除失败");
}
}
消息消费者(搜索服务)
1 )配置文件 修改 pinyougou-search-service 的 applicationContext-activemq-consumer.xml
2)代码实现 com.pinyougou.search.service.impl 包下创建监听类 ItemDeleteListener
/**
* 监听:用于删除索引库中记录
* @author Administrator
* /
@Component
public class ItemDeleteListener implements MessageListener{
@Autowired
private ItemSearchService itemSearchService;
@Override
public void onMessage(Message message) {
try {
ObjectMessage objectMessage= (ObjectMessage)message;
Long[] goodsIds = (Long[]) objectMessage.getObject();
System.out.println("ItemDeleteListener 监听接收到消息..."+goodsIds)
itemSearchService.deleteByGoodsIds(Arrays.asList(goodsIds));
System.out.println("成功删除索引库中的记录");
} catch (Exception e) {
e.printStackTrace();
}
}
}
其它增删改查模式都大同小异,再次不在重复赘述。