Spring-messaging-MessageChannel的子接口PollableChannel
目录
- PollableChannel的实现类QueueChannel(异步,点对点)
首先要约定几个词
同步:往通道发送消息,必须要等待接收消息的那方把消息处理完成,发送方的代码才能继续往下走
异步:直接扔消息进通道,不需要等待接收方处理消息,发送方的代码直接往下走
点对点:假设通道10个订阅者,往通道扔消息,只有1个订阅者才能收到,再次扔消息,也只有1个订阅者才能收到,这点可以做负载均衡,可以用来实现类似MQ的消费组场景
广播:假设通道有10个订阅者,往通道仍消息,10个订阅者全都能收到(注意:如果是同步,则10个订阅者是处理完1个,下1个才能收到消息,虽然是广播,但本质是逐个轮询)
PollableChannel的实现类QueueChannel(异步,点对点)
public static void main(String[] args) throws InterruptedException {PollableChannel messageChannel = new QueueChannel();((IntegrationObjectSupport)messageChannel).setComponentName("通道名字");Thread t = new Thread(() -> {while (true) {// 新启一个线程,在这一直拽消息,此方法会一直阻塞,如果没有消息的话Message<?> msg = messageChannel.receive();System.out.println("你刚刚输入了:" + msg.getPayload());}});t.start();// 从控制台输入消息Scanner scanner = new Scanner(System.in);System.out.print("请输入字符串:");while (true) {String input = scanner.nextLine(); // 读取整行输入(包括空格)Message<String> message = new GenericMessage<>(input);messageChannel.send(message);}}