实现商品的数据同步


一、后台系统

1、导入依赖

[html]  view plain  copy
  1. <dependency>  
  2.             <groupId>org.springframework.amqp</groupId>  
  3.             <artifactId>spring-rabbit</artifactId>  
  4.             <version>1.4.0.RELEASE</version>  
  5.         </dependency>  
  6.         <dependency>  
  7.             <groupId>com.rabbitmq</groupId>  
  8.             <artifactId>amqp-client</artifactId>  
  9.             <version>3.4.1</version>  
  10.         </dependency>  

2、编写配置文件applicationContext-rabbitmq

[html]  view plain  copy
  1. <pre name="code" class="html"><beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  3.     xsi:schemaLocation="http://www.springframework.org/schema/rabbit  
  4.     http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd  
  5.     http://www.springframework.org/schema/beans  
  6.     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">  
  7.   
  8.     <!-- 定义RabbitMQ的连接工厂 -->  
  9.     <rabbit:connection-factory id="connectionFactory"  
  10.         host="${rabbitmq.host}" port="${rabbitmq.port}" username="${rabbitmq.username}" password="${rabbitmq.password}"  
  11.         virtual-host="${rabbitmq.vhost}" />  
  12.       
  13.     <!-- 定义交换机 -->  
  14.     <rabbit:topic-exchange name="taotao-item-exchange" auto-declare="true" durable="true">  
  15.         <!-- 选择采用手动绑定队列 -->  
  16.     </rabbit:topic-exchange>  
  17.       
  18.     <!-- MQ的管理,包括队列、交换器等 -->  
  19.     <rabbit:admin connection-factory="connectionFactory"/>  
  20.       
  21.     <!-- 定义模板 -->  
  22.     <rabbit:template id="template" connection-factory="connectionFactory" exchange="taotao-item-exchange"/>  
  23.   
  24. </beans>  


 
  

3、service

[java]  view plain  copy
  1. package com.taotao.manage.service;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import org.apache.commons.lang3.StringUtils;  
  8. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.beans.factory.annotation.Value;  
  11. import org.springframework.stereotype.Service;  
  12.   
  13. import com.fasterxml.jackson.databind.ObjectMapper;  
  14. import com.github.abel533.entity.Example;  
  15. import com.github.pagehelper.PageInfo;  
  16. import com.taotao.common.service.ApiService;  
  17. import com.taotao.manage.pojo.Item;  
  18. import com.taotao.manage.pojo.ItemDesc;  
  19. import com.taotao.manage.pojo.ItemParamItem;  
  20.   
  21. @Service  
  22. public class ItemService extends BaseService<Item> {  
  23.   
  24.     // 注意:事务的转播性  
  25.     @Autowired  
  26.     private ItemDescService itemDescService;  
  27.   
  28.     @Autowired  
  29.     private ItemParamItemService itemParamItemService;  
  30.   
  31.     @Value("${TAOTAO_WEB_URL}")  
  32.     private String TAOTAO_WEB_URL;  
  33.       
  34.     @Autowired  
  35.     private ApiService apiService;  
  36.       
  37.     @Autowired  
  38.     private RabbitTemplate rabbitTemplate;  
  39.       
  40.     private static final ObjectMapper MAPPER = new ObjectMapper();  
  41.   
  42.     /** 
  43.      * 新增商品 
  44.      *  
  45.      * @param item 
  46.      * @param desc 
  47.      */  
  48.     public void saveItem(Item item, String desc, String itemParams) {  
  49.   
  50.         item.setStatus(1);// 初始状态  
  51.         item.setId(null);// 强制id为null,考虑到安全性  
  52.   
  53.         // 新增商品  
  54.         super.save(item);  
  55.   
  56.         // 新增商品描述数据  
  57.         ItemDesc itemDesc = new ItemDesc();  
  58.         itemDesc.setItemDesc(desc);  
  59.         itemDesc.setItemId(item.getId());  
  60.         this.itemDescService.save(itemDesc);  
  61.   
  62.         if (StringUtils.isNotEmpty(itemParams)) {// 不为空时创建数据  
  63.             ItemParamItem itemParamItem = new ItemParamItem();  
  64.             itemParamItem.setItemId(item.getId());  
  65.             itemParamItem.setParamData(itemParams);  
  66.             this.itemParamItemService.save(itemParamItem);  
  67.         }  
  68.           
  69.         //发送商品新增的消息到RabbitMQ  
  70.         sendMsg(item.getId(), "insert");  
  71.     }  
  72.   
  73.     public PageInfo<Item> queryItemList(Integer page, Integer rows) {  
  74.         Example example = new Example(Item.class);  
  75.         example.setOrderByClause("updated DESC");  
  76.         example.createCriteria().andNotEqualTo("status"3);  
  77.         return super.queryPageListByExample(example, page, rows);  
  78.     }  
  79.   
  80.     /** 
  81.      * 实现商品的逻辑删除 
  82.      *  
  83.      * @param ids 
  84.      */  
  85.     public void updateByIds(List<Object> ids) {  
  86.         Example example = new Example(Item.class);  
  87.         example.createCriteria().andIn("id", ids);  
  88.         Item item = new Item();  
  89.         item.setStatus(3);// 更改状态为3,说明该商品已经被删除  
  90.         super.getMapper().updateByExampleSelective(item, example);  
  91.           
  92.         for (Object object : ids) {  
  93.             //发送商品删除的消息到RabbitMQ  
  94.             sendMsg(Long.valueOf(object.toString()), "delete");  
  95.         }  
  96.     }  
  97.   
  98.     public void updateItem(Item item, String desc, ItemParamItem itemParamItem) {  
  99.         // 强制设置不能被更新的字段为null  
  100.         item.setStatus(null);  
  101.         item.setCreated(null);  
  102.         // 更新商品数据  
  103.         super.updateSelective(item);  
  104.   
  105.         // 更新商品描述数据  
  106.         ItemDesc itemDesc = new ItemDesc();  
  107.         itemDesc.setItemId(item.getId());  
  108.         itemDesc.setItemDesc(desc);  
  109.         this.itemDescService.updateSelective(itemDesc);  
  110.   
  111.         if (null != itemParamItem) {  
  112.             // 更新规格参数  
  113.             this.itemParamItemService.updateSelective(itemParamItem);  
  114.         }  
  115.   
  116. //        try {  
  117. //            // 通知其他系统商品已经更新  
  118. //            String url = TAOTAO_WEB_URL + "/item/cache/" + item.getId() + ".html";  
  119. //            this.apiService.doPost(url);  
  120. //        } catch (Exception e) {  
  121. //            e.printStackTrace();  
  122. //        }  
  123.           
  124.         //发送商品更新的消息到RabbitMQ  
  125.         sendMsg(item.getId(), "update");  
  126.     }  
  127.       
  128.     private void sendMsg(Long itemId,String type){  
  129.         try {  
  130.             Map<String, Object> msg = new HashMap<String, Object>();  
  131.             msg.put("itemId", itemId);  
  132.             msg.put("type", type);  
  133.             msg.put("created", System.currentTimeMillis());  
  134.             this.rabbitTemplate.convertAndSend("item." + type, MAPPER.writeValueAsString(msg));  
  135.         } catch (Exception e) {  
  136.             e.printStackTrace();  
  137.         }  
  138.     }  
  139.   
  140. }  

4、rabbitmq.properties

[html]  view plain  copy
  1. rabbitmq.host=127.0.0.1  
  2. rabbitmq.port=5672  
  3. rabbitmq.username=taotao  
  4. rabbitmq.password=taotao  
  5. rabbitmq.vhost=/taotao  
二、前台系统接收消息

1、导入同样的依赖

2、配置文件

[html]  view plain  copy
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  3.     xsi:schemaLocation="http://www.springframework.org/schema/rabbit  
  4.     http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd  
  5.     http://www.springframework.org/schema/beans  
  6.     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">  
  7.   
  8.     <!-- 定义RabbitMQ的连接工厂 -->  
  9.     <rabbit:connection-factory id="connectionFactory"  
  10.         host="${rabbitmq.host}" port="${rabbitmq.port}" username="${rabbitmq.username}" password="${rabbitmq.password}"  
  11.         virtual-host="${rabbitmq.vhost}" />  
  12.       
  13.     <!-- MQ的管理,包括队列、交换器等 -->  
  14.     <rabbit:admin connection-factory="connectionFactory"/>  
  15.       
  16.     <!-- 定义队列 -->  
  17.     <rabbit:queue name="taotao-web-item" auto-declare="true" durable="true"/>  
  18.       
  19.     <!-- 设置监听 -->  
  20.     <rabbit:listener-container connection-factory="connectionFactory">  
  21.         <rabbit:listener ref="itemMQHandler" method="execute" queue-names="taotao-web-item"/>  
  22.     </rabbit:listener-container>  
  23.   
  24. </beans>  

3、rabbitmq.properties

[html]  view plain  copy
  1. rabbitmq.host=127.0.0.1  
  2. rabbitmq.port=5672  
  3. rabbitmq.username=taotao  
  4. rabbitmq.password=taotao  
  5. rabbitmq.vhost=/taotao  
4、ItemMQHandler

[java]  view plain  copy
  1. package com.taotao.web.mq.handler;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Component;  
  7.   
  8. import com.fasterxml.jackson.databind.JsonNode;  
  9. import com.fasterxml.jackson.databind.ObjectMapper;  
  10. import com.taotao.common.service.RedisService;  
  11. import com.taotao.web.service.ItemService;  
  12.   
  13. @Component  
  14. public class ItemMQHandler {  
  15.   
  16.     private static final Logger LOGGER = LoggerFactory.getLogger(ItemMQHandler.class);  
  17.   
  18.     private static final ObjectMapper MAPPER = new ObjectMapper();  
  19.   
  20.     @Autowired  
  21.     private RedisService redisService;  
  22.   
  23.     public void execute(String msg) {  
  24.         if (LOGGER.isDebugEnabled()) {  
  25.             LOGGER.debug("接收到消息,MSG = {}", msg);  
  26.         }  
  27.         try {  
  28.             JsonNode jsonNode = MAPPER.readTree(msg);  
  29.             Long itemId = jsonNode.get("itemId").asLong();  
  30.             this.redisService.del(ItemService.REDIS_ITEM_KEY + itemId);  
  31.         } catch (Exception e) {  
  32.             LOGGER.error("处理消息出错! MSG = " + msg, e);  
  33.         }  
  34.     }  
  35.   
  36. }  
5、


三、搜索系统接收消息

1、导入同样的依赖

2、配置文件

[html]  view plain  copy
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  3.     xsi:schemaLocation="http://www.springframework.org/schema/rabbit  
  4.     http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd  
  5.     http://www.springframework.org/schema/beans  
  6.     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">  
  7.   
  8.     <!-- 定义RabbitMQ的连接工厂 -->  
  9.     <rabbit:connection-factory id="connectionFactory"  
  10.         host="${rabbitmq.host}" port="${rabbitmq.port}" username="${rabbitmq.username}" password="${rabbitmq.password}"  
  11.         virtual-host="${rabbitmq.vhost}" />  
  12.       
  13.     <!-- MQ的管理,包括队列、交换器等 -->  
  14.     <rabbit:admin connection-factory="connectionFactory"/>  
  15.       
  16.     <!-- 定义队列 -->  
  17.     <rabbit:queue name="taotao-search-item" auto-declare="true" durable="true"/>  
  18.       
  19.     <!-- 设置监听 -->  
  20.     <rabbit:listener-container connection-factory="connectionFactory">  
  21.         <rabbit:listener ref="itemMQHandler" method="execute" queue-names="taotao-search-item"/>  
  22.     </rabbit:listener-container>  
  23.   
  24. </beans>  

3、同样的rabbitmq.properties文件

4、ItemMQHandler

[java]  view plain  copy
  1. package com.taotao.search.mq.handler;  
  2.   
  3. import org.apache.commons.lang3.StringUtils;  
  4. import org.apache.solr.client.solrj.impl.HttpSolrServer;  
  5. import org.slf4j.Logger;  
  6. import org.slf4j.LoggerFactory;  
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.stereotype.Component;  
  9.   
  10. import com.fasterxml.jackson.databind.JsonNode;  
  11. import com.fasterxml.jackson.databind.ObjectMapper;  
  12. import com.taotao.search.bean.Item;  
  13. import com.taotao.search.service.ItemService;  
  14.   
  15. @Component  
  16. public class ItemMQHandler {  
  17.   
  18.     private static final Logger LOGGER = LoggerFactory.getLogger(ItemMQHandler.class);  
  19.   
  20.     private static final ObjectMapper MAPPER = new ObjectMapper();  
  21.   
  22.     @Autowired  
  23.     private HttpSolrServer httpSolrServer;  
  24.   
  25.     @Autowired  
  26.     private ItemService itemService;  
  27.   
  28.     public void execute(String msg) {  
  29.         if (LOGGER.isDebugEnabled()) {  
  30.             LOGGER.debug("接收到消息,MSG = {}", msg);  
  31.         }  
  32.         try {  
  33.             JsonNode jsonNode = MAPPER.readTree(msg);  
  34.             Long itemId = jsonNode.get("itemId").asLong();  
  35.             String type = jsonNode.get("type").asText();  
  36.             if (StringUtils.equals(type, "insert") || StringUtils.equals(type, "update")) {  
  37.                 // 查询商品的数据  
  38.                 Item item = this.itemService.queryItemById(itemId);  
  39.                 this.httpSolrServer.addBean(item);  
  40.   
  41.             } else if (StringUtils.equals(type, "delete")) {  
  42.                 this.httpSolrServer.deleteById(String.valueOf(itemId));  
  43.             }  
  44.             // 提交  
  45.             this.httpSolrServer.commit();  
  46.         } catch (Exception e) {  
  47.             LOGGER.error("处理消息出错! MSG = " + msg, e);  
  48.         }  
  49.     }  
  50.   
  51. }  
5、ItemService

[html]  view plain  copy
  1. package com.taotao.search.service;  
  2.   
  3. import org.apache.commons.lang3.StringUtils;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.beans.factory.annotation.Value;  
  6. import org.springframework.stereotype.Service;  
  7.   
  8. import com.fasterxml.jackson.databind.ObjectMapper;  
  9. import com.taotao.search.bean.Item;  
  10.   
  11. @Service  
  12. public class ItemService {  
  13.   
  14.     @Autowired  
  15.     private ApiService apiService;  
  16.   
  17.     @Value("${MANAGE_TAOTAO_URL}")  
  18.     private String MANAGE_TAOTAO_URL;  
  19.   
  20.     private static final ObjectMapper MAPPER = new ObjectMapper();  
  21.   
  22.     /**  
  23.      * 根据商品id查询商品数据  
  24.      *   
  25.      * @param itemId  
  26.      * @return  
  27.      */  
  28.     public Item queryItemById(Long itemId) {  
  29.         String url = MANAGE_TAOTAO_URL + "/rest/item/" + itemId;  
  30.         try {  
  31.             String jsonData = this.apiService.doGet(url);  
  32.             if (StringUtils.isEmpty(jsonData)) {  
  33.                 return null;  
  34.             }  
  35.             return MAPPER.readValue(jsonData, Item.class);  
  36.         } catch (Exception e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.         return null;  
  40.     }  
  41.   
  42.   
  43. }  
6、rabbitmq.properties文件加上MANAGE_TAOTAO_URL=http://manage.taotao.com

7、ApiService、applicationContext-httpclient.xml、httpclient.properties复制过来,前面笔记有。

8、绑定




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值