注解@TransactionalEventListener

例如 用户注册之后需要计算用户的邀请关系,递归操作。如果注册的时候包含多步验证,生成基本初始化数据,这时候我们通过mq发送消息来处理这个邀请关系,会出现一个问题,就是用户还没注册数据还没入库,邀请关系就开始执行,但是查不到数据,导致出错。

@TransactionalEventListener 可以实现事务的监听,可以在提交之后再进行操作。
——————————————
1.实体类

@Data
public class Customer {

    private Integer id;

    private String name;

}

2.监听的对象

import lombok.Getter;
import org.springframework.context.ApplicationEvent;

/**
 * fileName:RegCustomerEvent
 * description:
 * author: LJV
 * createTime:2022/8/19 14:41
 * version:1.0.0
 */
@Getter
public class RegCustomerEvent extends ApplicationEvent {

    private Customer customer;

    /***
     * @description 构造函数,用于设置消息体属性内容
     * @author 朱孝恒(javazhuxiaoheng @ 163.com)
     * @date 2022-03-17
     * @param customer 推送对象
     */
    public RegCustomerEvent(Customer customer) {
        super(customer);
        this.customer = customer;
    }

}

3.Spring事务事件发送, 用于调用ApplicationEventPublisher发布事件

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

/**
 * fileName:TranscationEventPublisher
 * description:Spring事务事件发送, 用于调用ApplicationEventPublisher发布事件
 * author: LJV
 * createTime:2022/8/19 14:58
 * version:1.0.0
 */
@Service
public class TranscationEventPublisher {

    /**
     * Spring事件发布器对象
     */
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /***
     * @description 发布数据生成事件
     * @author
     * @date 2022-03-17
     * @param customer
     */
    public void publishCustomerEvent(Customer customer) {
        applicationEventPublisher.publishEvent(new RegCustomerEvent(customer));
    }

}

4.消息事件监听器

package com.ljv.chat.event_;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * fileName:TranscationMessageListener
 * description: 消息事件监听器
 * author: LJV
 * createTime:2022/8/19 15:04
 * version:1.0.0
 */
@Component
@Slf4j
public class TranscationMessageListener {

    /***
     * @description 本地事务监听事件,事务完成后,发布一条推送订单给司机的MQTT消息
     * @author 朱孝恒(javazhuxiaoheng @ 163.com)
     * @date 2022-03-17
     * @param regCustomerEvent 消息事件主题
     */
    @Async  //如果使用该异步注解,则需要 @EnableAsync在主类
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void pushCustomer(RegCustomerEvent regCustomerEvent) {
        log.info("freightSendEvent: {}", regCustomerEvent);
        //业务逻辑
        System.out.println("---事件开始执行---");
    }
}

5.工具类

package com.ljv.chat.event_;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * spring工具类 方便在非spring管理环境中获取bean
 *
 * @author hupengnan
 */
@Component
public final class SpringUtils implements BeanFactoryPostProcessor
{
    /** Spring应用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
    {
        SpringUtils.beanFactory = beanFactory;
    }

    /**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     *
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException
    {
        return (T) beanFactory.getBean(name);
    }

    /**
     * 获取类型为requiredType的对象
     *
     * @param clz
     * @return
     * @throws BeansException
     *
     */
    public static <T> T getBean(Class<T> clz) throws BeansException
    {
        T result = (T) beanFactory.getBean(clz);
        return result;
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
     *
     * @param name
     * @return boolean
     */
    public static boolean containsBean(String name)
    {
        return beanFactory.containsBean(name);
    }

    /**
     * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
     *
     * @param name
     * @return boolean
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.isSingleton(name);
    }

    /**
     * @param name
     * @return Class 注册对象的类型
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.getType(name);
    }

    /**
     * 如果给定的bean名字在bean定义中有别名,则返回这些别名
     *
     * @param name
     * @return
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.getAliases(name);
    }
}

6.服务层接口

package com.ljv.chat.event_.service;

/**
 * fileName:Customer
 * description:
 * author: LJV
 * createTime:2022/8/19 16:36
 * version:1.0.0
 */
public interface CustomerService {
    void getCustomer();
}

7.服务层实现类

package com.ljv.chat.event_.service;

import com.ljv.chat.event_.Customer;
import com.ljv.chat.event_.SpringUtils;
import com.ljv.chat.event_.TranscationEventPublisher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * fileName:CustomerServiceImpl
 * description:
 * author: LJV
 * createTime:2022/8/19 16:38
 * version:1.0.0
 */
@Service
@Slf4j
public class CustomerServiceImpl implements CustomerService {

    @Override
    @Transactional
    public void getCustomer() {
        log.info("---业务开始执行---");
        Customer customer = new Customer();
        customer.setId(1);
        customer.setName("qweqwe");

        log.info("aaa");
        SpringUtils.getBean(TranscationEventPublisher.class).publishCustomerEvent(customer);
        log.info("ccc");
//        Thread.sleep(1000);
        try {
            TimeUnit.SECONDS.sleep(10);//秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("---业务执行结束---");
    }
}

8.控制层 进行测试

package com.ljv.chat.event_;

import com.ljv.chat.event_.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * fileName:Test
 * description:
 * author: LJV
 * createTime:2022/8/19 15:09
 * version:1.0.0
 */
@RestController
@RequestMapping("customer")
@Slf4j
public class TestController {

    @Autowired
    private CustomerService customerService;

    @GetMapping("getCustomer")
    public void getCustomer() throws InterruptedException {
        customerService.getCustomer();
    }

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容