分布与并行计算—生产者消费者模型RabbitMQ(Java)

连接工具

  public class ConnectionUtil {public static final String  QUEUE_NAME="firstQueue";private static final String RABBIT_HOST = "11";private static final String RABBIT_USERNAME = "";private static final String RABBIT_PASSWORD = "";private static Connection connection = null;public static int byteArrayToInt(byte[] b) {return   b[3] & 0xFF |(b[2] & 0xFF) << 8 |(b[1] & 0xFF) << 16 |(b[0] & 0xFF) << 24;}public static byte[] intToByteArray(int a) {return new byte[] {(byte) ((a >> 24) & 0xFF),(byte) ((a >> 16) & 0xFF),(byte) ((a >> 8) & 0xFF),(byte) (a & 0xFF)};}public static Connection getConnection() {if(connection == null) {ConnectionFactory connectionFactory = new ConnectionFactory();connectionFactory.setHost(RABBIT_HOST);connectionFactory.setUsername(RABBIT_USERNAME);connectionFactory.setPassword(RABBIT_PASSWORD);try {connection = connectionFactory.newConnection();} catch (IOException e) {e.printStackTrace();} catch (TimeoutException e) {e.printStackTrace();}}return connection;}}

消费者线程

public class Consumer implements Runnable {int j=0;int n;CountDownLatch countDownLatch;public Consumer( int n,CountDownLatch countDownLatch) {this.countDownLatch=countDownLatch;this.n = n;}@Overridepublic void run() {try {Connection connection = ConnectionUtil.getConnection();Channel channel = connection.createChannel();channel.basicQos(1);//能者多劳模式channel.queueDeclare(ConnectionUtil.QUEUE_NAME,true,false,false,null);DefaultConsumer consumer = new DefaultConsumer(channel){@Overridepublic void handleDelivery(String consumerTag, com.rabbitmq.client.Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {super.handleDelivery(consumerTag, envelope, properties, body);int cur=ConnectionUtil.byteArrayToInt(body);try {isPrime(cur);countDownLatch.countDown();/*  System.out.println(==1?"质数":"非质数");*/}finally {channel.basicAck(envelope.getDeliveryTag(),false);}}};channel.basicConsume(ConnectionUtil.QUEUE_NAME,false, consumer);} catch (IOException ioException) {ioException.printStackTrace();}}int isPrime(int n){	//返回1表示判断为质数,0为非质数,在此没有进行输入异常检测double n_sqrt;if(n==2 || n==3) return 1;if(n%6!=1 && n%6!=5) return 0;n_sqrt=Math.floor(Math.sqrt((float)n));for(int i=5;i<=n_sqrt;i+=6){if(n%(i)==0 | n%(i+2)==0) return 0;}return 1;}}

启动入口

public class Model {public  static void excute(int consumerNum,int num){long s=System.currentTimeMillis();CountDownLatch countDownLatch=new CountDownLatch(num);ExecutorService executorService= Executors.newFixedThreadPool(consumerNum);for(int i=0;i<consumerNum;i++){executorService.execute(new Consumer(num/consumerNum,countDownLatch));}try {countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}System.out.println((System.currentTimeMillis()-s)/1000+"s");executorService.shutdown();}public static void main(String[] args) {excute(4,100);}
}

生产者线程

public class Producer implements Runnable{int n;CountDownLatch countDownLatch;public Producer(int n, CountDownLatch countDownLatch) {this.n = n;this.countDownLatch=countDownLatch;}@Overridepublic void run() {Connection connection= ConnectionUtil.getConnection();try {Channel channel=connection.createChannel();channel.queueDeclare(ConnectionUtil.QUEUE_NAME,true,false,false,null);Random ra =new Random();for(int i=0;i<n;i++){try {/*  System.out.println(this.toString()+i+"生产");*/channel.basicPublish("",ConnectionUtil.QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,ConnectionUtil.intToByteArray(ra.nextInt(2000000000)+1));countDownLatch.countDown();/*    System.out.println("生产"+blockingQueue.size());*/} catch (Exception e) {e.printStackTrace();}}} catch (IOException ioException) {ioException.printStackTrace();}System.out.println("生产者完成");}
}

启动入口

public class test {public  static void excute(int producerNum,int num){CountDownLatch countDownLatch=new CountDownLatch(producerNum);ExecutorService executorService= Executors.newFixedThreadPool(num);for(int i=0;i<producerNum;i++){executorService.execute(new Producer(num/producerNum,countDownLatch));}try {countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}executorService.shutdown();
/*for(int i=0;i<consumerNum;i++){new Thread(new Consumer(blockingQueue,num/consumerNum,countDownLatch)).start();}
*/}public static void main(String[] args) {long s=System.currentTimeMillis();excute(2,100);System.out.println((double) (System.currentTimeMillis()-s)/1000);}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392160.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

飞腾 linux 内核,FT2004-Xenomai

移植Xenomai到基于飞腾FT2004 CPU的FT Linux系统1 目前飞腾FT2000/4相关设备驱动还没有开源&#xff0c;需要先联系飞腾软件生态部获取FT Linux源代码2 如需在x86交叉编译arm64内核&#xff0c;推荐使用Linaro gcc编译器&#xff0c;链接如下&#xff1a;https://releases.lina…

使用管道符组合使用命令_如何使用管道的魔力

使用管道符组合使用命令Surely you have heard of pipelines or ETL (Extract Transform Load), or seen some method in a library, or even heard of any tool to create pipelines. However, you aren’t using it yet. So, let me introduce you to the fantastic world of…

关于网页授权的两种scope的区别说明

关于网页授权的两种scope的区别说明 1、以snsapi_base为scope发起的网页授权&#xff0c;是用来获取进入页面的用户的openid的&#xff0c;并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页&#xff08;往往是业务页面&#xff09; 2、以snsapi_userinfo为…

安卓流行布局开源库_如何使用流行度在开源库之间进行选择

安卓流行布局开源库by Ashish Singal通过Ashish Singal 如何使用流行度在开源库之间进行选择 (How to choose between open source libraries using popularity) Through my career as a product manager, I’ve worked closely with engineers to build many technology prod…

TCP/IP分析(一) 协议概述

各协议层分工明确 转载于:https://www.cnblogs.com/HonkerYblogs/p/11247604.html

window 下分linux分区,如何在windows9x下访问linux分区

1. 简 介Linux 内 核 支 持 众 多 的 文 件 系 统 类 型, 目 前 它 可 以 读 写( 至 少 是 读) 大 部 分 的 文 件 系 统.Linux 经 常 与Microsoft Windows 共 存 于 一 个 系 统 或 者 硬 盘 中.Linux 对windows9x/NT 的 文 件 系 统 支 持 的 很 好, 反 之 你 想 在windows 下…

C# new关键字和对象类型转换(双括号、is操作符、as操作符)

一、new关键字 CLR要求所有的对象都通过new来创建,代码如下: Object objnew Object(); 以下是new操作符做的事情 1、计算类型及其所有基类型(一直到System.Object,虽然它没有定义自己的实例字段)中定义的所有实例字段需要的字节数.堆上每个对象都需要一些额外的成员,包括“类型…

JDBC01 利用JDBC连接数据库【不使用数据库连接池】

目录&#xff1a; 1 什么是JDBC 2 JDBC主要接口 3 JDBC编程步骤【学渣版本】 5 JDBC编程步骤【学神版本】 6 JDBC编程步骤【学霸版本】 1 什么是JDBC JDBC是JAVA提供的一套标准连接数据库的接口&#xff0c;规定了连接数据库的步骤和功能&#xff1b;不同的数据库提供商提供了一…

leetcode 778. 水位上升的泳池中游泳(并查集)

在一个 N x N 的坐标方格 grid 中&#xff0c;每一个方格的值 grid[i][j] 表示在位置 (i,j) 的平台高度。 现在开始下雨了。当时间为 t 时&#xff0c;此时雨水导致水池中任意位置的水位为 t 。你可以从一个平台游向四周相邻的任意一个平台&#xff0c;但是前提是此时水位必须…

2020年十大币预测_2020年十大商业智能工具

2020年十大币预测In the rapidly growing world of today, when technology is expanding at a rate like never before, there are plenty of tools and skills to explore, learn, and master. In this digital and data age, Business Information and Intelligence have cl…

如何使用MySQL和JPA使用Spring Boot构建Rest API

Hi Everyone! For the past year, I have been learning JavaScript for full-stack web development. For a change, I started to master Java — the powerful Object Oriented Language.嗨&#xff0c;大家好&#xff01; 在过去的一年中&#xff0c;我一直在学习用于全栈W…

翻译

令 $m>n>1$ 为正整数. 一个集合含有 $m$ 个给定的实数. 我们从中选取任意 $n$ 个数, 记作 $a_1$, $a_2$, $\dotsc$, $a_n$, 并提问: 是否 $a_1<a_2<\dotsb < a_n$ 正确? 证明: 我们可以最多问 $n!-n^22n-2m(n-1)(1\lfloor \log_{n} m \rfloor)-m$ 个问题&#…

720 智能硬件与 LeanCloud 云端的默契协作

【 玩转 LeanCloud 】开发者经验分享&#xff1a; 作者&#xff1a;谢子超 720技术负责人&#xff0c;从业十余年&#xff0c;一直负责软件开发工作。 我们的产品是与监控和改善室内空气质量相关的智能硬件&#xff0c;我们使用 LeanCloud 平台已经有 2 年多了&#xff0c;借此…

linux cifs windows 慢,windows上使用dockerIO特别慢有没有更优的解决方案?

复制一个大佬的回答Docker for Windows是在Hyper-V虚拟机上跑Linux&#xff0c;文件挂载是通过SMB协议从Windows挂载到Linux&#xff0c;文件读写都经过网络&#xff0c;遇到Laravel这种每次启动就要加载几百个文件的框架&#xff0c;文件性能问题就尤其明显。最好的验证方法就…

编译原理—词法分析器(Java)

1.当运行程序时&#xff0c;程序会读取项目下的program.txt文件 2. 程序将会逐行读取program.txt中的源程序&#xff0c;进行词法分析&#xff0c;并将分析的结果输出。 3. 如果发现错误&#xff0c;程序将会中止读取文件进行分析&#xff0c;并输出错误提示 所用单词的构词规…

【BZOJ4653】[Noi2016]区间 双指针法+线段树

【BZOJ4653】[Noi2016]区间 Description 在数轴上有 n个闭区间 [l1,r1],[l2,r2],...,[ln,rn]。现在要从中选出 m 个区间&#xff0c;使得这 m个区间共同包含至少一个位置。换句话说&#xff0c;就是使得存在一个 x&#xff0c;使得对于每一个被选中的区间 [li,ri]&#xff0c;都…

为什么我们需要使用Pandas新字符串Dtype代替文本数据对象

We have to represent every bit of data in numerical values to be processed and analyzed by machine learning and deep learning models. However, strings do not usually come in a nice and clean format and require a lot preprocessing.我们必须以数值表示数据的每…

递归方程组解的渐进阶的求法——代入法

递归方程组解的渐进阶的求法——代入法 用这个办法既可估计上界也可估计下界。如前面所指出&#xff0c;方法的关键步骤在于预先对解答作出推测&#xff0c;然后用数学归纳法证明推测的正确性。 例如&#xff0c;我们要估计T(n)的上界&#xff0c;T(n)满足递归方程&#xff1a;…

【转载】C# 理解泛型

术语表 generics&#xff1a;泛型type-safe&#xff1a;类型安全collection: 集合compiler&#xff1a;编译器run time&#xff1a;程序运行时object: 对象.NET library&#xff1a;.Net类库value type: 值类型box: 装箱unbox: 拆箱implicity: 隐式explicity: 显式linked list:…

javascript 作用_JavaScript承诺如何从内到外真正发挥作用

javascript 作用One of the most important questions I faced in interviews was how promises are implemented. Since async/await is becoming more popular, you need to understand promises.我在采访中面临的最重要的问题之一是如何实现承诺。 由于异步/等待变得越来越流…