26rabbitMq在项目中的使用

生产者,当有变化的数据时,需要通知前台系统,搜索系统(消费者)

一对多

26rabbitMq在项目中的使用_第1张图片

1后台系统整合spring(生产者:生产者到交换机)

1-1》导入依赖需要配置在taotao-manage-service中



       org.springframework.amqp

       spring-rabbit

       1.4.0.RELEASE

 


   1-2》添加配置文件

26rabbitMq在项目中的使用_第2张图片

applicationContext-rabbitmq.xml:(因为作为生产者,只需要和交换机建立联系,所以没有消费者,队列)




	
	
	
	
	
	
	
	

rabbitmq.properties

26rabbitMq在项目中的使用_第3张图片

1-3》在后台系统ItemService中发送消息

在修改商品信息时,需要作为生产者发给交换机

26rabbitMq在项目中的使用_第4张图片

 

================================================

2消费者(队列,消费者)

2-1》添加依赖

26rabbitMq在项目中的使用_第5张图片

2-2》编写配置文件

 

26rabbitMq在项目中的使用_第6张图片

applicationContext-rabblitmq.xml




	
	
	
	
	
	
	
	
	
	
		
	


消费者(接受消息)MqItemMsgHandler 类下的getMsg

26rabbitMq在项目中的使用_第7张图片

 

=============================================

应用:后台商品数据发生变化,要通知前台系统和搜索系统进行数据的更新

前台系统:

xml

26rabbitMq在项目中的使用_第8张图片

类:

**
 * 监听后台系统发送的消息,并处理
 */
public class ItemMessageListener {
    @Autowired
    private HttpSolrServer server;
    @Autowired
    private ItemService itemService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public void consume(String msg) {
        try {
            // 解析消息
            JsonNode jsonNode = MAPPER.readTree(msg);
            Long itemId = jsonNode.get("itemId").asLong();
            String type = jsonNode.get("type").asText();

            // 判断操作类型
            if (StringUtils.equals("insert", type) || StringUtils.equals("update", type)) {
                // 根据ID查询商品
                Item item = this.itemService.queryItemById(itemId);
                if(item != null){
                    // 新增数据到solr
                    this.server.addBean(item);
                    this.server.commit();
                }
            } else if (StringUtils.equals("delete", type)) {
                // 删除solr数据
                this.server.deleteById(itemId.toString());
                this.server.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

你可能感兴趣的:(淘淘)