ComboTransaction.java 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package org.jeecg.config.transactional;
  2. import org.apache.commons.lang.StringUtils;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Component;
  5. import java.util.concurrent.Callable;
  6. import java.util.stream.Stream;
  7. /**
  8. * 功能描述:
  9. *
  10. * @Author: chenchuang
  11. * @Date: 2022/3/31 16:56
  12. */
  13. @Component
  14. public class ComboTransaction {
  15. @Autowired
  16. private Db1TxBroker db1TxBroker;
  17. @Autowired
  18. private Db2TxBroker db2TxBroker;
  19. public <V> V inCombinedTx(Callable<V> callable, String[] transactions) {
  20. if (callable == null) {
  21. return null;
  22. }
  23. Callable<V> combined = Stream.of(transactions)
  24. .filter(ele -> !StringUtils.isEmpty(ele))
  25. .distinct()
  26. .reduce(callable, (r, tx) -> {
  27. switch (tx) {
  28. case DbTxConstants.DB1_TX:
  29. return () -> db1TxBroker.inTransaction(r);
  30. case DbTxConstants.DB2_TX:
  31. return () -> db2TxBroker.inTransaction(r);
  32. default:
  33. return null;
  34. }
  35. }, (r1, r2) -> r2);
  36. try {
  37. return combined.call();
  38. } catch (RuntimeException e) {
  39. throw e;
  40. } catch (Exception e) {
  41. throw new RuntimeException(e);
  42. }
  43. }
  44. }