Using RabbitMQ to achieve commodity data synchronization

【Producer side】

One, add dependencies

<dependency>

 <的groupId> org.springframework.amqp </的groupId>  

  <artifactId>Spring Bunny</artifactId>

</dependency>


Second, the configured applicationContext-rabbitmq.xml file

<?xml version =“1.0” encoding =“UTF-8” ?>
 < beans xmlns =“http://www.springframework.org/schema/beans”
 xmlns:xsi =“http://www.w3.org/2001 / XMLSchema-instance“ 
 xmlns:rabbit =”http://www.springframework.org/schema/rabbit“
 xsi :schemaLocation =”http://www.springframework.org/schema/beans 
        http://www.springframework。 org / schema / beans / spring-beans.xsd 
        http://www.springframework.org/schema/rabbit 
        http://www.springframework.org/schema/rabbit/spring-rabbit.xsd“ >
 <! - 连接工厂 - >
 <                     
        :connection-factory id ="connectionFactory" host ="${rabbitmq.host}"
  port ="${rabbitmq.port}" username ="${rabbitmq.username}"
  password ="${rabbitmq.password}" virtual -host ="${rabbitmq.vhost}" />
  <! - Rabbit management, automatic management of queues and exchanges ->
  < rabbit :admin connection-factory ="connectionFactory" />
  <! - The exchange uses topic type here ->
  < rabbit : topic-exchange name ="JESSES_ITEM_EXCHANGE" />
  <! - Rabbit's template, which provides an API for manipulating messages, requires specifying connection factories and switches ->
  < rabbit : templateID                                                                      
        
        =“rabbitTemplate”
 connection-factory =“connectionFactory” exchange =“JESSES_ITEM_EXCHANGE” />
 </ beans >                     

Third, write a method to send a message.

private void sendMessage ( Item item , String type ) {
  try {
  Map < String , Object > msg = new HashMap <>();
 msg . put ( "data" , item . getId ());
 msg . put ( "type" , type );
 msg . put ( "timestamp" , system . currentTimeMillis ());
                                    
        this . rabbitTemplate . convertAndSend ( "Item" + type , JsonUtils . toString ( msg ));
     } catch ( JsonProcessingException e ) {
  e . printStackTrace ();
 /* The exception of the service layer is generally thrown, if you try, the transaction will not be rolled back.  But try it here. Even if the message fails to be sent, the transaction should not be rolled back to fail the modification.  should be handled here. Write code to resend. * /  }
  }                    



【Consumer side】

1. Import the can package of Spring Rabbit

Second, the configured applicationContext-rabbitmq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/rabbit 
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

    <!--连接工厂-->
    <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                               port="${rabbitmq.port}" username="${rabbitmq.username}"
                               password="${rabbitmq.password}" virtual-host="${rabbitmq.vhost}" />
    <!--Rabbit的管理,自动管理队列和交换机-->
    <rabbit:admin connection-factory="connectionFactory" />
    <!--定义队列-->
    <rabbit:queue name="JESSES_WEB_ITEM_QUEUE" />
    <!--消息监听者-->
    <bean id="itemMessageListener" class="com.jesses.web.mq.listener.ItemMessageListener" />
    <rabbit:listener-container connection-factory="connectionFactory">
        <rabbit:listener ref="itemMessageListener" method="consume" 
                         queue-names="JESSES_WEB_ITEM_QUEUE"/>
    </rabbit:listener-container>
</beans>

三、写消费者实现消费消息。

package com.jesses.web.mq.listener;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jesses.web.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * 监听商品信息的一个消费者
 */
public class ItemMessageListener {

    @Autowired
    private ItemService itemService;

    private static final ObjectMapper MAPPER=new ObjectMapper();

    //消费方法
    public void consume(String msg){
        Long itemId=0L;
        try {
            JsonNode jsonNode = MAPPER.readTree(msg);//读取传过来的字符串读成树节点
            itemId = jsonNode.get("data").asLong();//用保存时的key获取指定节点。
        } catch (IOException e) {
            e.printStackTrace();
            返回;
        }
 //删除缓存
 this itemService deleteCache itemId );
    }
 }                

PS:队列和交换机的绑定可以在配置中定义,也可以在控制面板手动去做。

手动去做可以避免日后再改代码,利于解耦合。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325566315&siteId=291194637