基于activemq的分布式事务解决方案

1、分布式事务出现场景

场景描述:支付宝转账余额宝

分布式事务必须满足的条件:

1、远程RPC调用,支付宝和余额宝存在接口调用

2、支付宝和余额宝使用不同的数据库

如图:

2、分布式事务解决方案

1、基于数据库XA协议的两段提交

XA协议是数据库支持的一种协议,其核心是一个事务管理器用来统一管理两个分布式数据库,如图

事务管理器负责跟支付宝数据库和余额宝数据库打交道,一旦有一个数据库连接失败,另一个数据库的操作就不会进行,一个数据库操作失败就会导致另一个数据库回滚,只有他们全部成功两个数据库的事务才会提交。

基于XA协议的两段和三段提交是一种严格的安全确认机制,其安全性是非常高的,但是保证安全性的前提是牺牲了性能,这个就是分布式系统里面的CAP理论,做任何架构的前提需要有取舍。所以基于XA协议的分布式事务并发性不高,不适合高并发场景。

2、基于activemq的解决方案

如图:

1、支付宝扣款成功时往message表插入消息

2、message表有message_id(流水id,标识夸系统的一次转账操作),status(confirm,unconfirm)

3、timer扫描message表的unconfirm状态记录往activemq插入消息

4、余额宝收到消息消费消息时先查询message表如果有记录就不处理如果没记录就进行数据库增款操作

5、如果余额宝数据库操作成功往余额宝message表插入消息,表字段跟支付宝message一致

6、如果5操作成功,回调支付宝接口修改message表状态,把unconfirm状态转换成confirm状态

问题描述:

1、支付宝设计message表的目的

如果支付宝往activemq插入消息而余额宝消费消息异常,有可能是消费消息成功而事务操作异常,有可能是网络异常等等不确定因素。如果出现异常而activemq收到了确认消息的信号,这时候activemq中的消息是删除了的,消息丢失了。设置message表就是有一个消息存根,activemq中消息丢失了message表中的消息还在。解决了activemq消息丢失问题

2、余额宝设计message表的目的

当余额宝消费成功并且数据库操作成功时,回调支付宝的消息确认接口,如果回调接口时出现异常导致支付宝状态修改失败还是unconfirm状态,这时候还会被timer扫描到,又会往activemq插入消息,又会被余额宝消费一边,但是这条消息已经消费成功了的只是回调失败而已,所以就需要有一个这样的message表,当余额宝消费时先插入message表,如果message根据message_id能查询到记录就说明之前这条消息被消费过就不再消费只需要回调成功即可,如果查询不到消息就消费这条消息继续数据库操作,数据库操作成功就往message表插入消息。  这样就解决了消息重复消费问题,这也是消费端的幂等操作。

基于消息中间件的分布式事务是最理想的分布式事务解决方案,兼顾了安全性和并发性!

接下来贴代码:

支付宝代码:


  
  
  1. @Controller
  2. @RequestMapping( "/order")
  3. public class OrderController {
  4. /**
  5. * @Description TODO
  6. * @param @return 参数
  7. * @return String 返回类型
  8. * @throws
  9. *
  10. * userID:转账的用户ID
  11. * amount:转多少钱
  12. */
  13. @Autowired
  14. @Qualifier( "activemq")
  15. OrderService orderService;
  16. @RequestMapping( "/transfer")
  17. public @ResponseBody String transferAmount(String userId,String messageId, int amount) {
  18. try {
  19. orderService.updateAmount(amount,messageId, userId);
  20. }
  21. catch (Exception e) {
  22. e.printStackTrace();
  23. return "===============================transferAmount failed===================";
  24. }
  25. return "===============================transferAmount successfull===================";
  26. }
  27. @RequestMapping( "/callback")
  28. public String callback(String param) {
  29. JSONObject parse = JSONObject.parseObject(param);
  30. String respCode = parse.getString( "respCode");
  31. if(! "OK".equalsIgnoreCase(respCode)) {
  32. return null;
  33. }
  34. try {
  35. orderService.updateMessage(param);
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. return "fail";
  39. }
  40. return "ok";
  41. }
  42. }

  
  
  1. public interface OrderService {
  2. public void updateAmount(int amount, String userId,String messageId);
  3. public void updateMessage(String param);
  4. }

  
  
  1. @Service( "activemq")
  2. @Transactional(rollbackFor = Exception.class)
  3. public class OrderServiceActivemqImpl implements OrderService {
  4. Logger logger = LoggerFactory.getLogger(getClass());
  5. @Autowired
  6. JdbcTemplate jdbcTemplate;
  7. @Autowired
  8. JmsTemplate jmsTemplate;
  9. @Override
  10. public void updateAmount(final int amount, final String messageId, final String userId) {
  11. String sql = "update account set amount = amount - ?,update_time=now() where user_id = ?";
  12. int count = jdbcTemplate.update(sql, new Object[]{amount, userId});
  13. if (count == 1) {
  14. //插入到消息记录表
  15. sql = "insert into message(user_id,message_id,amount,status) values (?,?,?,?)";
  16. int row = jdbcTemplate.update(sql, new Object[]{userId,messageId,amount, "unconfirm"});
  17. if(row == 1) {
  18. //往activemq中插入消息
  19. jmsTemplate.send( "zg.jack.queue", new MessageCreator() {
  20. @Override
  21. public Message createMessage(Session session) throws JMSException {
  22. com.zhuguang.jack.bean.Message message = new com.zhuguang.jack.bean.Message();
  23. message.setAmount(Integer.valueOf(amount));
  24. message.setStatus( "unconfirm");
  25. message.setUserId(userId);
  26. message.setMessageId(messageId);
  27. return session.createObjectMessage(message);
  28. }
  29. });
  30. }
  31. }
  32. }
  33. @Override
  34. public void updateMessage(String param) {
  35. JSONObject parse = JSONObject.parseObject(param);
  36. String messageId = parse.getString( "messageId");
  37. String sql = "update message set status = ? where message_id = ?";
  38. int count = jdbcTemplate.update(sql, new Object[]{ "confirm",messageId});
  39. if(count == 1) {
  40. logger.info(messageId + " callback successfull");
  41. }
  42. }
  43. }

activemq.xml


  
  
  1. <?xml version= "1.0" encoding= "UTF-8"?>
  2. <beans xmlns= "http://www.springframework.org/schema/beans"
  3. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:amq= "http://activemq.apache.org/schema/core"
  5. xmlns:jms= "http://www.springframework.org/schema/jms"
  6. xmlns:context= "http://www.springframework.org/schema/context"
  7. xmlns:mvc= "http://www.springframework.org/schema/mvc"
  8. xsi:schemaLocation= "
  9. http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context-4.1.xsd
  13. http://www.springframework.org/schema/mvc
  14. http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
  15. http://www.springframework.org/schema/jms
  16. http://www.springframework.org/schema/jms/spring-jms-4.1.xsd
  17. http://activemq.apache.org/schema/core
  18. http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd"
  19. >
  20. <context:component-scan base- package= "com.zhuguang.jack" />
  21. <mvc:annotation-driven />
  22. <amq:connectionFactory id= "amqConnectionFactory"
  23. brokerURL= "tcp://192.168.88.131:61616"
  24. userName= "system"
  25. password= "manager" />
  26. <!-- 配置JMS连接工长 -->
  27. <bean id= "connectionFactory"
  28. class= "org.springframework.jms.connection.CachingConnectionFactory">
  29. <constructor-arg ref= "amqConnectionFactory" />
  30. <property name= "sessionCacheSize" value= "100" />
  31. </bean>
  32. <!-- 定义消息队列(Queue) -->
  33. <bean id= "demoQueueDestination" class= "org.apache.activemq.command.ActiveMQQueue">
  34. <!-- 设置消息队列的名字 -->
  35. <constructor-arg>
  36. <value>zg.jack.queue</value>
  37. </constructor-arg>
  38. </bean>
  39. <!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 -->
  40. <bean id= "jmsTemplate" class= "org.springframework.jms.core.JmsTemplate">
  41. <property name= "connectionFactory" ref= "connectionFactory" />
  42. <property name= "defaultDestination" ref= "demoQueueDestination" />
  43. <property name= "receiveTimeout" value= "10000" />
  44. <!-- true是topic, false是queue,默认是 false,此处显示写出 false -->
  45. <property name= "pubSubDomain" value= "false" />
  46. </bean>
  47. </beans>

spring-dispatcher.xml


  
  
  1. <beans xmlns= "http://www.springframework.org/schema/beans"
  2. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p"
  3. xmlns:context= "http://www.springframework.org/schema/context"
  4. xmlns:task= "http://www.springframework.org/schema/task"
  5. xmlns:aop= "http://www.springframework.org/schema/aop"
  6. xmlns:tx= "http://www.springframework.org/schema/tx"
  7. xmlns:util= "http://www.springframework.org/schema/util" xmlns:mvc= "http://www.springframework.org/schema/mvc"
  8. xsi:schemaLocation= "
  9. http://www.springframework.org/schema/util
  10. http://www.springframework.org/schema/util/spring-util-3.2.xsd
  11. http://www.springframework.org/schema/beans
  12. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  13. http://www.springframework.org/schema/context
  14. http://www.springframework.org/schema/context/spring-context-3.2.xsd
  15. http://www.springframework.org/schema/mvc
  16. http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  17. http://www.springframework.org/schema/task
  18. http://www.springframework.org/schema/task/spring-task-3.0.xsd
  19. http://www.springframework.org/schema/tx
  20. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  21. http://www.springframework.org/schema/aop
  22. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  23. ">
  24. <!-- 引入同文件夹下的redis属性配置文件 -->
  25. <!-- 解决springMVC响应数据乱码 text/plain就是响应的时候原样返回数据-->
  26. < import resource= "../activemq/activemq.xml"/>
  27. <!--<context:property-placeholder ignore-unresolvable= "true" location= "classpath:config/core/core.properties,classpath:config/redis/redis-config.properties" />-->
  28. <bean id= "propertyConfigurerForProject1" class= "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  29. <property name= "order" value= "1" />
  30. <property name= "ignoreUnresolvablePlaceholders" value= "true" />
  31. <property name= "location">
  32. <value>classpath:config/core/core.properties</value>
  33. </property>
  34. </bean>
  35. <mvc:annotation-driven>
  36. <mvc:message-converters register-defaults= "true">
  37. <bean class= "org.springframework.http.converter.StringHttpMessageConverter">
  38. <property name= "supportedMediaTypes" value = "text/plain;charset=UTF-8" />
  39. </bean>
  40. </mvc:message-converters>
  41. </mvc:annotation-driven>
  42. <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
  43. <bean id= "mappingJacksonHttpMessageConverter" class= "org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
  44. <property name= "supportedMediaTypes">
  45. <list>
  46. <value>text/html;charset=UTF- 8</value>
  47. </list>
  48. </property>
  49. </bean>
  50. <!-- 开启controller注解支持 -->
  51. <!-- 注:如果base- package=com.avicit 则注解事务不起作用 TODO 读源码 -->
  52. <context:component-scan base- package= "com.zhuguang">
  53. </context:component-scan>
  54. <mvc:view-controller path= "/" view-name= "redirect:/index" />
  55. <bean
  56. class= "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
  57. <bean id= "handlerAdapter"
  58. class= "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  59. </bean>
  60. <bean
  61. class= "org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  62. <property name= "mediaTypes">
  63. <map>
  64. <entry key= "json" value= "application/json" />
  65. <entry key= "xml" value= "application/xml" />
  66. <entry key= "html" value= "text/html" />
  67. </map>
  68. </property>
  69. <property name= "viewResolvers">
  70. <list>
  71. <bean class= "org.springframework.web.servlet.view.BeanNameViewResolver" />
  72. <bean class= "org.springframework.web.servlet.view.UrlBasedViewResolver">
  73. <property name= "viewClass" value= "org.springframework.web.servlet.view.JstlView" />
  74. <property name= "prefix" value= "/" />
  75. <property name= "suffix" value= ".jsp" />
  76. </bean>
  77. </list>
  78. </property>
  79. </bean>
  80. <!-- 支持上传文件 -->
  81. <!-- 控制器异常处理 -->
  82. <bean id= "exceptionResolver"
  83. class= "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  84. <property name= "exceptionMappings">
  85. <props>
  86. <prop key= "java.lang.Exception">
  87. error
  88. </prop>
  89. </props>
  90. </property>
  91. </bean>
  92. <bean id= "dataSource" class= "com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method= "close">
  93. <property name= "driverClass">
  94. <value>${jdbc.driverClassName}</value>
  95. </property>
  96. <property name= "jdbcUrl">
  97. <value>${jdbc.url}</value>
  98. </property>
  99. <property name= "user">
  100. <value>${jdbc.username}</value>
  101. </property>
  102. <property name= "password">
  103. <value>${jdbc.password}</value>
  104. </property>
  105. <property name= "minPoolSize" value= "10" />
  106. <property name= "maxPoolSize" value= "100" />
  107. <property name= "maxIdleTime" value= "1800" />
  108. <property name= "acquireIncrement" value= "3" />
  109. <property name= "maxStatements" value= "1000" />
  110. <property name= "initialPoolSize" value= "10" />
  111. <property name= "idleConnectionTestPeriod" value= "60" />
  112. <property name= "acquireRetryAttempts" value= "30" />
  113. <property name= "breakAfterAcquireFailure" value= "false" />
  114. <property name= "testConnectionOnCheckout" value= "false" />
  115. <property name= "acquireRetryDelay">
  116. <value> 100</value>
  117. </property>
  118. </bean>
  119. <bean id= "jdbcTemplate" class= "org.springframework.jdbc.core.JdbcTemplate">
  120. <property name= "dataSource" ref= "dataSource"></property>
  121. </bean>
  122. <bean id= "transactionManager" class= "org.springframework.jdbc.datasource.DataSourceTransactionManager">
  123. <property name= "dataSource" ref= "dataSource"/>
  124. </bean>
  125. <tx:annotation-driven transaction-manager= "transactionManager" proxy-target- class= "true" />
  126. <aop:aspectj-autoproxy expose-proxy= "true"/>
  127. </beans>

logback.xml


  
  
  1. <?xml version= "1.0" encoding= "UTF-8"?>
  2. <!--
  3. scan:当此属性设置为 true时,配置文件如果发生改变,将会被重新加载,默认值为 true
  4. scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒当scan为 true时,此属性生效。默认的时间间隔为 1分钟。
  5. debug:当此属性设置为 true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为 false
  6. -->
  7. <configuration scan= "false" scanPeriod= "60 seconds" debug= "false">
  8. <!-- 定义日志的根目录 -->
  9. <!-- <property name= "LOG_HOME" value= "/app/log" /> -->
  10. <!-- 定义日志文件名称 -->
  11. <property name= "appName" value= "netty"></property>
  12. <!-- ch.qos.logback.core.ConsoleAppender 表示控制台输出 -->
  13. <appender name= "stdout" class= "ch.qos.logback.core.ConsoleAppender">
  14. <Encoding>UTF- 8</Encoding>
  15. <!--
  16. 日志输出格式:%d表示日期时间,%thread表示线程名,%- 5level:级别从左显示 5个字符宽度
  17. %logger{ 50} 表示logger名字最长 50个字符,否则按照句点分割。 %msg:日志消息,%n是换行符
  18. -->
  19. <encoder>
  20. <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %- 5level %logger{ 50} - %msg%n</pattern>
  21. </encoder>
  22. </appender>
  23. <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
  24. <appender name= "appLogAppender" class= "ch.qos.logback.core.rolling.RollingFileAppender">
  25. <Encoding>UTF- 8</Encoding>
  26. <!-- 指定日志文件的名称 -->
  27. <file>${appName}.log</file>
  28. <!--
  29. 当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名
  30. TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动。
  31. -->
  32. <rollingPolicy class= "ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  33. <!--
  34. 滚动时产生的文件的存放位置及文件名称 %d{yyyy-MM-dd}:按天进行日志滚动
  35. %i:当文件大小超过maxFileSize时,按照i进行文件滚动
  36. -->
  37. <fileNamePattern>${appName}-%d{yyyy-MM-dd}-%i.log</fileNamePattern>
  38. <!--
  39. 可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件。假设设置每天滚动,
  40. 且maxHistory是 365,则只保存最近 365天的文件,删除之前的旧文件。注意,删除旧文件是,
  41. 那些为了归档而创建的目录也会被删除。
  42. -->
  43. <MaxHistory> 365</MaxHistory>
  44. <!--
  45. 当日志文件超过maxFileSize指定的大小是,根据上面提到的%i进行日志文件滚动 注意此处配置SizeBasedTriggeringPolicy是无法实现按文件大小进行滚动的,必须配置timeBasedFileNamingAndTriggeringPolicy
  46. -->
  47. <timeBasedFileNamingAndTriggeringPolicy class= "ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
  48. <maxFileSize> 100MB</maxFileSize>
  49. </timeBasedFileNamingAndTriggeringPolicy>
  50. </rollingPolicy>
  51. <!--
  52. 日志输出格式:%d表示日期时间,%thread表示线程名,%- 5level:级别从左显示 5个字符宽度 %logger{ 50} 表示logger名字最长 50个字符,否则按照句点分割。 %msg:日志消息,%n是换行符
  53. -->
  54. <encoder>
  55. <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %- 5level ] [ %logger{ 50} : %line ] - %msg%n</pattern>
  56. </encoder>
  57. </appender>
  58. <!--
  59. logger主要用于存放日志对象,也可以定义日志类型、级别
  60. name:表示匹配的logger类型前缀,也就是包的前半部分
  61. level:要记录的日志级别,包括 TRACE < DEBUG < INFO < WARN < ERROR
  62. additivity:作用在于children-logger是否使用 rootLogger配置的appender进行输出, false:表示只用当前logger的appender-ref, true:表示当前logger的appender-ref和rootLogger的appender-ref都有效
  63. -->
  64. <!-- <logger name= "edu.hyh" level= "info" additivity= "true">
  65. <appender-ref ref= "appLogAppender" />
  66. </logger> -->
  67. <!--
  68. root与logger是父子关系,没有特别定义则默认为root,任何一个类只会和一个logger对应,
  69. 要么是定义的logger,要么是root,判断的关键在于找到这个logger,然后判断这个logger的appender和level。
  70. -->
  71. <root level= "debug">
  72. <appender-ref ref= "stdout" />
  73. <appender-ref ref= "appLogAppender" />
  74. </root>
  75. </configuration>

2、余额宝代码


  
  
  1. package com.zhuguang.jack.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.zhuguang.jack.service.OrderService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. @Controller
  9. @RequestMapping( "/order")
  10. public class OrderController {
  11. /**
  12. * @Description TODO
  13. * @param @return 参数
  14. * @return String 返回类型
  15. * @throws
  16. *
  17. * 模拟银行转账
  18. * userID:转账的用户ID
  19. * amount:转多少钱
  20. */
  21. @Autowired
  22. OrderService orderService;
  23. @RequestMapping( "/transfer")
  24. public @ResponseBody String transferAmount(String userId, String amount) {
  25. try {
  26. orderService.updateAmount(Integer.valueOf(amount), userId);
  27. }
  28. catch (Exception e) {
  29. e.printStackTrace();
  30. return "===============================transferAmount failed===================";
  31. }
  32. return "===============================transferAmount successfull===================";
  33. }
  34. }

 消息监听器


  
  
  1. package com.zhuguang.jack.listener;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.zhuguang.jack.service.OrderService;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.http.client.SimpleClientHttpRequestFactory;
  8. import org.springframework.stereotype.Service;
  9. import org.springframework.transaction.annotation.Transactional;
  10. import org.springframework.web.client.RestTemplate;
  11. import javax.jms.JMSException;
  12. import javax.jms.Message;
  13. import javax.jms.MessageListener;
  14. import javax.jms.ObjectMessage;
  15. @Service( "queueMessageListener")
  16. public class QueueMessageListener implements MessageListener {
  17. private Logger logger = LoggerFactory.getLogger(getClass());
  18. @Autowired
  19. OrderService orderService;
  20. @Transactional(rollbackFor = Exception.class)
  21. @Override
  22. public void onMessage(Message message) {
  23. if (message instanceof ObjectMessage) {
  24. ObjectMessage objectMessage = (ObjectMessage) message;
  25. try {
  26. com.zhuguang.jack.bean.Message message1 = (com.zhuguang.jack.bean.Message) objectMessage.getObject();
  27. String userId = message1.getUserId();
  28. int count = orderService.queryMessageCountByUserId(userId);
  29. if (count == 0) {
  30. orderService.updateAmount(message1.getAmount(), message1.getUserId());
  31. orderService.insertMessage(message1.getUserId(), message1.getMessageId(), message1.getAmount(), "ok");
  32. } else {
  33. logger.info( "异常转账");
  34. }
  35. RestTemplate restTemplate = createRestTemplate();
  36. JSONObject jo = new JSONObject();
  37. jo.put( "messageId", message1.getMessageId());
  38. jo.put( "respCode", "OK");
  39. String url = "http://jack.bank_a.com:8080/alipay/order/callback?param="
  40. + jo.toJSONString();
  41. restTemplate.getForObject(url, null);
  42. } catch (JMSException e) {
  43. e.printStackTrace();
  44. throw new RuntimeException( "异常");
  45. }
  46. }
  47. }
  48. public RestTemplate createRestTemplate() {
  49. SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
  50. simpleClientHttpRequestFactory.setConnectTimeout( 3000);
  51. simpleClientHttpRequestFactory.setReadTimeout( 2000);
  52. return new RestTemplate(simpleClientHttpRequestFactory);
  53. }
  54. }

  
  
  1. package com.zhuguang.jack.service;
  2. public interface OrderService {
  3. public void updateAmount(int amount, String userId);
  4. public int queryMessageCountByUserId(String userId);
  5. public int insertMessage(String userId,String messageId,int amount,String status);
  6. }

  
  
  1. package com.zhuguang.jack.service;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.client.SimpleClientHttpRequestFactory;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import org.springframework.stereotype.Service;
  8. import org.springframework.transaction.annotation.Transactional;
  9. import org.springframework.web.client.RestTemplate;
  10. @Service
  11. @Transactional(rollbackFor = Exception.class)
  12. public class OrderServiceImpl implements OrderService {
  13. private Logger logger = LoggerFactory.getLogger(getClass());
  14. @Autowired
  15. JdbcTemplate jdbcTemplate;
  16. /*
  17. * 更新数据库表,把账户余额减去amountd
  18. */
  19. @Override
  20. public void updateAmount(int amount, String userId) {
  21. //1、农业银行转账3000,也就说农业银行jack账户要减3000
  22. String sql = "update account set amount = amount + ?,update_time=now() where user_id = ?";
  23. int count = jdbcTemplate.update(sql, new Object[] {amount, userId});
  24. if (count != 1) {
  25. throw new RuntimeException( "订单创建失败,农业银行转账失败!");
  26. }
  27. }
  28. public RestTemplate createRestTemplate() {
  29. SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
  30. simpleClientHttpRequestFactory.setConnectTimeout( 3000);
  31. simpleClientHttpRequestFactory.setReadTimeout( 2000);
  32. return new RestTemplate(simpleClientHttpRequestFactory);
  33. }
  34. @Override
  35. public int queryMessageCountByUserId(String messageId) {
  36. String sql = "select count(*) from message where message_id = ?";
  37. int count = jdbcTemplate.queryForInt(sql, new Object[]{messageId});
  38. return count;
  39. }
  40. @Override
  41. public int insertMessage(String userId, String message_id,int amount, String status) {
  42. String sql = "insert into message(user_id,message_id,amount,status) values(?,?,?)";
  43. int count = jdbcTemplate.update(sql, new Object[]{userId, message_id,amount, status});
  44. if(count == 1) {
  45. logger.info( "Ok");
  46. }
  47. return count;
  48. }
  49. }

activemq.xml


  
  
  1. <?xml version= "1.0" encoding= "UTF-8"?>
  2. <beans xmlns= "http://www.springframework.org/schema/beans"
  3. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:amq= "http://activemq.apache.org/schema/core"
  5. xmlns:jms= "http://www.springframework.org/schema/jms"
  6. xmlns:context= "http://www.springframework.org/schema/context"
  7. xmlns:mvc= "http://www.springframework.org/schema/mvc"
  8. xsi:schemaLocation= "
  9. http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context-4.1.xsd
  13. http://www.springframework.org/schema/mvc
  14. http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
  15. http://www.springframework.org/schema/jms
  16. http://www.springframework.org/schema/jms/spring-jms-4.1.xsd
  17. http://activemq.apache.org/schema/core
  18. http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd"
  19. >
  20. <context:component-scan base- package= "com.zhuguang.jack" />
  21. <mvc:annotation-driven />
  22. <amq:connectionFactory id= "amqConnectionFactory"
  23. brokerURL= "tcp://192.168.88.131:61616"
  24. userName= "system"
  25. password= "manager" />
  26. <!-- 配置JMS连接工长 -->
  27. <bean id= "connectionFactory"
  28. class= "org.springframework.jms.connection.CachingConnectionFactory">
  29. <constructor-arg ref= "amqConnectionFactory" />
  30. <property name= "sessionCacheSize" value= "100" />
  31. </bean>
  32. <!-- 定义消息队列(Queue) -->
  33. <bean id= "demoQueueDestination" class= "org.apache.activemq.command.ActiveMQQueue">
  34. <!-- 设置消息队列的名字 -->
  35. <constructor-arg>
  36. <value>zg.jack.queue</value>
  37. </constructor-arg>
  38. </bean>
  39. <!-- 显示注入消息监听容器(Queue),配置连接工厂,监听的目标是demoQueueDestination,监听器是上面定义的监听器 -->
  40. <bean id= "queueListenerContainer"
  41. class= "org.springframework.jms.listener.DefaultMessageListenerContainer">
  42. <property name= "connectionFactory" ref= "connectionFactory" />
  43. <property name= "destination" ref= "demoQueueDestination" />
  44. <property name= "messageListener" ref= "queueMessageListener" />
  45. </bean>
  46. <!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 -->
  47. <bean id= "jmsTemplate" class= "org.springframework.jms.core.JmsTemplate">
  48. <property name= "connectionFactory" ref= "connectionFactory" />
  49. <property name= "defaultDestination" ref= "demoQueueDestination" />
  50. <property name= "receiveTimeout" value= "10000" />
  51. <!-- true是topic, false是queue,默认是 false,此处显示写出 false -->
  52. <property name= "pubSubDomain" value= "false" />
  53. </bean>
  54. </beans>

OK~~~~~~~~~~~~大功告成!!!,  如果大家觉得满意并且对技术感兴趣请加群:171239762, 纯技术交流群,非诚勿扰。

                        <li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#csdnc-thumbsup"></use>
                        </svg><span class="name">点赞</span>
                        <span class="count">6</span>
                        </a></li>
                        <li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;popu_824&quot;}"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-csdnc-Collection-G"></use>
                        </svg><span class="name">收藏</span></a></li>
                        <li class="tool-item tool-active is-share"><a href="javascript:;"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-csdnc-fenxiang"></use>
                        </svg>分享</a></li>
                        <!--打赏开始-->
                                                <!--打赏结束-->
                                                <li class="tool-item tool-more">
                            <a>
                            <svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
                            </a>
                            <ul class="more-box">
                                <li class="item"><a class="article-report">文章举报</a></li>
                            </ul>
                        </li>
                                            </ul>
                </div>
                            </div>
            <div class="person-messagebox">
                <div class="left-message"><a href="https://blog.csdn.net/luoyang_java">
                    <img src="https://profile.csdnimg.cn/2/F/E/3_luoyang_java" class="avatar_pic" username="luoyang_java">
                                            <img src="https://g.csdnimg.cn/static/user-reg-year/1x/4.png" class="user-years">
                                    </a></div>
                <div class="middle-message">
                                        <div class="title"><span class="tit"><a href="https://blog.csdn.net/luoyang_java" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}" target="_blank">黄山技术猿</a></span>
                                            </div>
                    <div class="text"><span>发布了106 篇原创文章</span> · <span>获赞 34</span> · <span>访问量 4万+</span></div>
                </div>
                                <div class="right-message">
                                            <a href="https://im.csdn.net/im/main.html?userName=luoyang_java" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信
                        </a>
                                                            <a class="btn btn-sm  bt-button personal-watch" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}">关注</a>
                                    </div>
                            </div>
                    </div>
    </article>
    
发布了5 篇原创文章 · 获赞 0 · 访问量 258

1、分布式事务出现场景

猜你喜欢

转载自blog.csdn.net/weixin_32822759/article/details/104355531