Spring Boot Event 观察者模式

时间:2022-08-05
本文章向大家介绍Spring Boot Event 观察者模式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

event 使用ApplicationEvent和ApplicationListener

// event
public class OrderProductEvent extends ApplicationEvent {
    public OrderProductEvent(Object source, String orderId) {
        super(source);

        this.orderId = orderId;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    private String orderId;
}

// listener
@Component
public class OrderProductListener implements ApplicationListener<OrderProductEvent> {
    @Async  // 异步支持
    @Override
    public void onApplicationEvent(OrderProductEvent event) {
        String orderId = event.getOrderId();
        long start = System.currentTimeMillis();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println(String.format("threadId %d, check order %s, takes %d ms", Thread.currentThread().getId(), orderId, end-start));
    }
}

event 使用@EventListener

public class MsgEvent {
    public MsgEvent(String orderId) {
        this.orderId = orderId;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    private String orderId;
}

@Component
public class MsgListener {
    @Async  // 异步支持
    @EventListener(MsgEvent.class)
    public void sendMsg(MsgEvent event) {
        String orderId = event.getOrderId();
        long start = System.currentTimeMillis();

        System.out.println(String.format("threadId %d, send message", Thread.currentThread().getId()));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println(String.format("threadId %d, send message %s, %d ms", Thread.currentThread().getId(), orderId, (end-start)));
    }
}

service

@Service
public class OrderService {
    private final ApplicationContext applicationContext;

    @Autowired
    public OrderService(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public String buyOrder(String orderId) {
        long start = System.currentTimeMillis();

        // publish event
        applicationContext.publishEvent(new OrderProductEvent(this, orderId));

        long end = System.currentTimeMillis();
        System.out.println(String.format("threadId %d, completed, %d ms", Thread.currentThread().getId(), end - start));
        return "success";
    }

    public String buyOrder2(String orderId) {
        long start = System.currentTimeMillis();

        // publish event
        applicationContext.publishEvent(new MsgEvent(orderId));

        long end = System.currentTimeMillis();
        System.out.println(String.format("threadId %d, completed, %d ms", Thread.currentThread().getId(), end - start));
        return "success";
    }
}
@EnableAsync   // 异步支持
@SpringBootApplication
public class SpringeventApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringeventApplication.class, args);
	}

}

测试

@SpringBootTest
class SpringeventApplicationTests {
	@Autowired
	private OrderService orderService;

	@Test
	public void buyOrderTest() {
		System.out.println(String.format("thread id %d", Thread.currentThread().getId()));
		orderService.buyOrder("12344");
		System.out.println("completed.");
	}

	@Test
	public void buyOrder2Test() {
		System.out.println(String.format("thread id %d", Thread.currentThread().getId()));
		orderService.buyOrder2("12344");
		System.out.println("completed.");
	}
}

参考:
https://zhuanlan.zhihu.com/p/541552814?utm_oi=963461047566483456

原文地址:https://www.cnblogs.com/mryux/p/16555593.html