一、全局异常处理
1、处理思路
- 创建全局异常处理器
public class GlobalExceptionReslover implements HandlerExceptionResolver {
Logger logger = LoggerFactory.getLogger(GlobalExceptionReslover.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //写日志文件 logger.error("系统发生异常", ex); //发邮件、发短信 //Jmail:可以查找相关的资料 //需要在购买短信。调用第三方接口即可。 //展示错误页面 ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("message", "系统发生异常,请稍后重试"); modelAndView.setViewName("error/exception"); return modelAndView; }
} |
- Springmvc中配置异常处理器
二、activeMQ
1、页面更新数据如何同步索引库
方案一:在taotao-manager中,添加商品的业务逻辑中,添加一个同步索引库的业务逻辑。
缺点:业务逻辑耦合度高,业务拆分不明确
方案二:业务逻辑在taotao-search中实现,调用服务在taotao-manager实现。业务逻辑分开。
缺点:服务之间的耦合度变高。服务的启动有先后顺序。
方案三:使用消息队列。MQ是一个消息中间件。
同步索引库 Consumer |
MQ是一个消息中间件,ActiveMQ、RabbitMQ、kafka
2、JMS
ActiveMQ 是Apache出品,ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现。
- 基本概念
JMS是java的消息服务,JMS的客户端之间可以通过JMS服务进行异步的消息传输。 - 消息模型
○ Point-to-Point(P2P)
○ Publish/Subscribe(Pub/Sub) - P2P
- P2P模式图
- 涉及到的概念
- 消息队列(Queue)
- 发送者(Sender)
- 接收者(Receiver)
- 每个消息都被发送到一个特定的队列,接收者从队列中获取消息。队列保留着消息,直到他们被消费或超时。
- P2P的特点
- 每个消息只有一个消费者(Consumer)(即一旦被消费,消息就不再在消息队列中)
- 发送者和接收者之间在时间上没有依赖性,也就是说当发送者发送了消息之后,不管接收者有没有正在运行,它不会影响到消息被发送到队列
- 接收者在成功接收消息之后需向队列应答成功
如果你希望发送的每个消息都应该被成功处理的话,那么你需要P2P模式。
- Pub/Sub
- Pub/Sub模式图
- 涉及到的概念
- 主题(Topic)
- 发布者(Publisher)
- 订阅者(Subscriber)
客户端将消息发送到主题。多个发布者将消息发送到Topic,系统将这些消息传递给多个订阅者。
- Pub/Sub的特点
- 每个消息可以有多个消费者
- 发布者和订阅者之间有时间上的依赖性。针对某个主题(Topic)的订阅者,它必须创建一个订阅者之后,才能消费发布者的消息,而且为了消费消息,订阅者必须保持运行的状态。
- 为了缓和这样严格的时间相关性,JMS允许订阅者创建一个可持久化的订阅。这样,即使订阅者没有被激活(运行),它也能接收到发布者的消息。
如果你希望发送的消息可以不被做任何处理、或者被一个消息者处理、或者可以被多个消费者处理的话,那么可以采用Pub/Sub模型
- 消息的消费
在JMS中,消息的产生和消息是异步的。对于消费来说,JMS的消息者可以通过两种方式来消费消息。
○ 同步
订阅者或接收者调用receive方法来接收消息,receive方法在能够接收到消息之前(或超时之前)将一直阻塞
○ 异步
订阅者或接收者可以注册为一个消息监听器。当消息到达之后,系统自动调用监听器的onMessage方法。 - JMS编程模型
(1) ConnectionFactory
创建Connection对象的工厂,针对两种不同的jms消息模型,分别有QueueConnectionFactory和TopicConnectionFactory两种。可以通过JNDI来查找ConnectionFactory对象。
(2) Destination
Destination的意思是消息生产者的消息发送目标或者说消息消费者的消息来源。对于消息生产者来说,它的Destination是某个队列(Queue)或某个主题(Topic);对于消息消费者来说,它的Destination也是某个队列或主题(即消息来源)。
所以,Destination实际上就是两种类型的对象:Queue、Topic可以通过JNDI来查找Destination。
(3) Connection
Connection表示在客户端和JMS系统之间建立的链接(对TCP/IP socket的包装)。Connection可以产生一个或多个Session。跟ConnectionFactory一样,Connection也有两种类型:QueueConnection和TopicConnection。
(4) Session
Session是我们操作消息的接口。可以通过session创建生产者、消费者、消息等。Session提供了事务的功能。当我们需要使用session发送/接收多个消息时,可以将这些发送/接收动作放到一个事务中。同样,也分QueueSession和TopicSession。
(5) 消息的生产者
消息生产者由Session创建,并用于将消息发送到Destination。同样,消息生产者分两种类型:QueueSender和TopicPublisher。可以调用消息生产者的方法(send或publish方法)发送消息。
(6) 消息消费者
消息消费者由Session创建,用于接收被发送到Destination的消息。两种类型:QueueReceiver和TopicSubscriber。可分别通过session的createReceiver(Queue)或createSubscriber(Topic)来创建。当然,也可以session的creatDurableSubscriber方法来创建持久化的订阅者。
(7) MessageListener
消息监听器。如果注册了消息监听器,一旦消息到达,将自动调用监听器的onMessage方法。EJB中的MDB(Message-Driven Bean)就是一种MessageListener。 - 企业消息系统的好处
我们先来看看下图,应用程序A将Message发送到服务器上,然后应用程序B从服务器中接收A发来的消息,通过这个图我们一起来分析一下JMS的好处:
- 提供消息灵活性
- 松散耦合
- 异步性
3、代码实现
- Producer
生产者:生产消息,发送端。
把jar包添加到工程中。使用5.11.2版本的jar包。
第一步:创建ConnectionFactory对象,需要指定服务端ip及端口号。
第二步:使用ConnectionFactory对象创建一个Connection对象。
第三步:开启连接,调用Connection对象的start方法。
第四步:使用Connection对象创建一个Session对象。
第五步:使用Session对象创建一个Destination对象(topic、queue),此处创建一个Queue对象。
第六步:使用Session对象创建一个Producer对象。
第七步:创建一个Message对象,创建一个TextMessage对象。
第八步:使用Producer对象发送消息。
第九步:关闭资源。
@Test public void testQueueProducer() throws Exception { // 第一步:创建ConnectionFactory对象,需要指定服务端ip及端口号。 //brokerURL服务器的ip及端口号 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.25.168:61616"); // 第二步:使用ConnectionFactory对象创建一个Connection对象。 Connection connection = connectionFactory.createConnection(); // 第三步:开启连接,调用Connection对象的start方法。 connection.start(); // 第四步:使用Connection对象创建一个Session对象。 //第一个参数:是否开启事务。true:开启事务,第二个参数忽略。 //第二个参数:当第一个参数为false时,才有意义。消息的应答模式。1、自动应答2、手动应答。一般是自动应答。 Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 第五步:使用Session对象创建一个Destination对象(topic、queue),此处创建一个Queue对象。 //参数:队列的名称。 Queue queue = session.createQueue("test-queue"); // 第六步:使用Session对象创建一个Producer对象。 MessageProducer producer = session.createProducer(queue); // 第七步:创建一个Message对象,创建一个TextMessage对象。 /*TextMessage message = new ActiveMQTextMessage(); message.setText("hello activeMq,this is my first test.");*/ TextMessage textMessage = session.createTextMessage("hello activeMq,this is my first test."); // 第八步:使用Producer对象发送消息。 producer.send(textMessage); // 第九步:关闭资源。 producer.close(); session.close(); connection.close(); } |
- Consumer
消费者:接收消息。
第一步:创建一个ConnectionFactory对象。
第二步:从ConnectionFactory对象中获得一个Connection对象。
第三步:开启连接。调用Connection对象的start方法。
第四步:使用Connection对象创建一个Session对象。
第五步:使用Session对象创建一个Destination对象。和发送端保持一致queue,并且队列的名称一致。
第六步:使用Session对象创建一个Consumer对象。
第七步:接收消息。
第八步:打印消息。
第九步:关闭资源
@Test public void testQueueConsumer() throws Exception { // 第一步:创建一个ConnectionFactory对象。 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.25.168:61616"); // 第二步:从ConnectionFactory对象中获得一个Connection对象。 Connection connection = connectionFactory.createConnection(); // 第三步:开启连接。调用Connection对象的start方法。 connection.start(); // 第四步:使用Connection对象创建一个Session对象。 Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 第五步:使用Session对象创建一个Destination对象。和发送端保持一致queue,并且队列的名称一致。 Queue queue = session.createQueue("test-queue"); // 第六步:使用Session对象创建一个Consumer对象。 MessageConsumer consumer = session.createConsumer(queue); // 第七步:接收消息。 consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { try { TextMessage textMessage = (TextMessage) message; String text = null; //取消息的内容 text = textMessage.getText(); // 第八步:打印消息。 System.out.println(text); } catch (JMSException e) { e.printStackTrace(); } } }); //等待键盘输入 System.in.read(); // 第九步:关闭资源 consumer.close(); session.close(); connection.close(); }
|
4、AcitveMQ与spring进行整合
4.1、整合消息生产者
在resource/spring/applicationContext-activeMQ.xml创建applicationContext-activeMQ.xml文件:
其具体内容为:
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.2.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-4.2.xsd">
<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->
<beanid="targetConnectionFactory"class="org.apache.activemq.ActiveMQConnectionFactory">
<propertyname="brokerURL" value="tcp://192.168.1.110:61616" />
</bean>
<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory-->
<beanid="connectionFactory"
class="org.springframework.jms.connection.SingleConnectionFactory">
<!-- 目标ConnectionFactory对应真实的可以产生JMSConnection的ConnectionFactory -->
<propertyname="targetConnectionFactory"ref="targetConnectionFactory" />
</bean>
<!-- 配置生产者 -->
<!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
<beanid="jmsTemplate"class="org.springframework.jms.core.JmsTemplate">
<!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
<propertyname="connectionFactory" ref="connectionFactory" />
</bean>
<!--这个是队列目的地,点对点的 -->
<beanid="queueDestination"class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg>
<value>spring-queue</value>
</constructor-arg>
</bean>
<!--这个是主题目的地,一对多的 -->
<beanid="topicDestination"class="org.apache.activemq.command.ActiveMQTopic">
<constructor-argvalue="itemAddtopic" />
</bean>
</beans>
然后在代码中实现:
@Service
publicclass ItemServiceImpl implements ItemService {
@Autowired
private JmsTemplate jmsTemplate;//注入jms对象
@Resource
private Destination topicDestination;//注入目的
@Override
publicE3Result addItem(TbItem item, String desc) {
//生成商品id
finallong itemId = IDUtils.genItemId();
//补全item的属性
item.setId(itemId);
//1-正常,2-下架,3-删除
item.setStatus((byte)1);
item.setCreated(newDate());
item.setUpdated(newDate());
//向商品表插入数据
itemMapper.insert(item);
//创建一个商品描述表对应的pojo对象。
TbItemDescitemDesc = new TbItemDesc();
//补全属性
itemDesc.setItemId(itemId);
itemDesc.setItemDesc(desc);
itemDesc.setCreated(newDate());
itemDesc.setUpdated(newDate());
//向商品描述表插入数据
itemDescMapper.insert(itemDesc);
//发送商品添加消息
jmsTemplate.send(topicDestination,new MessageCreator() {
@Override
publicMessage createMessage(Session session) throws JMSException {
TextMessagetextMessage = session.createTextMessage(itemId + "");
returntextMessage;
}
});
//返回成功
returnE3Result.ok();
}
}
4.2整合消息消费者
在resource/spring/applicationContext-activeMQ.xml创建applicationContext-activeMQ.xml文件:
其具体内容为:
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.2.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-4.2.xsd">
<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->
<beanid="targetConnectionFactory"class="org.apache.activemq.ActiveMQConnectionFactory">
<propertyname="brokerURL" value="tcp://192.168.1.110:61616" />
</bean>
<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory-->
<beanid="connectionFactory"
class="org.springframework.jms.connection.SingleConnectionFactory">
<!-- 目标ConnectionFactory对应真实的可以产生JMSConnection的ConnectionFactory -->
<propertyname="targetConnectionFactory"ref="targetConnectionFactory" />
</bean>
<!-- 接收消息 -->
<!--这个是队列目的地,点对点的 -->
<beanid="queueDestination"class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg>
<value>spring-queue</value>
</constructor-arg>
</bean>
<!--这个是主题目的地,一对多的 -->
<beanid="topicDestination"class="org.apache.activemq.command.ActiveMQTopic">
<constructor-argvalue="topic" />
</bean>
<!-- 配置监听器 -->
<beanid="myMessageListener"class="cn.e3mall.search.listener.MyMessageListener" />
<!-- 消息监听容器 -->
<beanclass="org.springframework.jms.listener.DefaultMessageListenerContainer">
<propertyname="connectionFactory" ref="connectionFactory" />
<propertyname="destination" ref="queueDestination" />
<propertyname="messageListener" ref="myMessageListener" />
</bean>
<beanid="itemAddMessageListener"class="cn.e3mall.search.listener.ItemAddMessageListener" />
<!-- 消息监听容器 -->
<beanclass="org.springframework.jms.listener.DefaultMessageListenerContainer">
<propertyname="connectionFactory" ref="connectionFactory" />
<propertyname="destination" ref="topicDestination" />
<propertyname="messageListener" ref="itemAddMessageListener" />
</bean>
</beans>
监听器
publicclass MyMessageListener implements MessageListener {
@Override
publicvoid onMessage(Message message) {
//取消息内容
TextMessagetextMessage = (TextMessage) message;
try{
Stringtext = textMessage.getText();
System.out.println(text);
}catch (JMSException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
收到监听信息,将消息更新入solr
publicclass ItemAddMessageListener implements MessageListener {
@Autowired
privateItemMapper itemMapper;
@Autowired
privateSolrServer solrServer;
@Override
publicvoid onMessage(Message message) {
try{
//从消息中取商品id
TextMessagetextMessage = (TextMessage) message;
Stringtext = textMessage.getText();
LongitemId = new Long(text);
//等待事务提交
Thread.sleep(1000);
//根据商品id查询商品信息
SearchItemsearchItem = itemMapper.getItemById(itemId);
//创建一个文档对象
SolrInputDocumentdocument = new SolrInputDocument();
//向文档对象中添加域
document.addField("id",searchItem.getId());
document.addField("item_title",searchItem.getTitle());
document.addField("item_sell_point",searchItem.getSell_point());
document.addField("item_price",searchItem.getPrice());
document.addField("item_image",searchItem.getImage());
document.addField("item_category_name",searchItem.getCategory_name());
//把文档写入索引库
solrServer.add(document);
//提交
solrServer.commit();
}catch (Exception e) {
e.printStackTrace();
}
}
}