赞
踩
在这个案例中我们会启动两个工作线程,一个消息发送线程,两个工作线程。然后在发送线程中不断发送消息,验证两个工作线程是以何种方式拿到消息的。
public class ExerciseT { private static final String QUEUE_NAME = "hello"; public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(You host address); factory.setUsername(username); factory.setPassword(password); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); //Receive messages from console Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String message = scanner.next(); channel.basicPublish("", QUEUE_NAME, null,message.getBytes()); System.out.println("Message has delivered:" + message); } } }
@Slf4j public class ExerciseW { private static final String QUEUE_NAME = "hello"; public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("192.168.121.36"); factory.setUsername("admin"); factory.setPassword("123"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); //lambda expression DeliverCallback deliverCallback = (consumerTag, message) -> { log.info("Worker1 has receive message:"+new String(message.getBody()),"UTF-8"); }; //lambda expression CancelCallback cancelCallback = consumerTag -> { log.info("Worker1 message has been canceled!"); }; channel.basicConsume(QUEUE_NAME,false,deliverCallback,cancelCallback); } }
启动另外一个工作线程的方式就是直接把上面那个工作线程中的Worker1改成worker2就行了。
在idea中设置允许并行运行即可,如下如所示
运行效果如下图所示:
消息发送线程:发送44,55,66,77
接收消息线程效果图1:
接收消息线程效果图2:
结论:消息发送线程,发送消息时工作线程会轮询得到消息发送线程发送的消息,这是一种公平的策略,但是这种方式效率较低,在实际工作中一般采用不公平的策略 。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。