RabbitMQ的消息模式

面试题:RabbitMQ 有哪几种消息模式? Rabbitmq 是使用 Erlang 语言开发的开源消息队列系统,基于 AMQP 实现,是一种应用程序对应用程序的通信方法,应用程序通过读写出入队列的消息来通信,而无需专用连接来链接它们。消息传递指的是应用程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此通信,直接调用通常是指远程过程调用的技术。 阅读详情

1、消息保证100%的投递

生产端的可靠性投递
1,保障消息的成功发出
2,保障MQ节点的成功接收
3,发送端收到MQ节点(Broker)确认应答
4,善的消息进行补偿机制

BAT/TMD互联网大厂的解决方案
1,消息落库,对消息状态进行打标
在这里插入图片描述
流程:

第1步:将订单入库,创建一条MSG(状态为0) 入MSG DB库
第2步:将消息发出去
第3步:监听消息应答(来自Broker)
第4步:修改消息的状态为1(成功)
第5步:分布式定时任务抓取状态为0的消息
第6步:将状态为0的消息重发
第7步:如果尝试了3次(可按实际情况修改)以上则将状态置为2(消息投递失败状态)

2, 消息的延迟投递,做二次确认,回调检查

在这里插入图片描述

第1步:首先业务数据落库,成功才后第一次消息发送
第2步:紧着着发送第2条消息(可以用于寻找第1条消息),用于延迟(可能2,3分钟后才发送)消息投递检查
第3步:Broker端收到消息后,消费端进行消息处理
第4步:处理成功后,发送confirm消息
第5步:收到confirm消息后,将消息进行持久化存储
第6步:收到了delay消息,检查DB数据库,若对应的第1条消息已处理完成,则不做任何事情;若收到了delay消息,检查DB数据库,发现对应的第1条消息处理失败(或无记录),则发送重传命令到上游服务,循环第1步

2、幂等性概念

幂等性:
我们可以借鉴数据库的乐观锁机制
比如我们执行一条更新库存的SQL语句
Update t_repository set count = count -1,version = version + 1 where version = 1
Elasticsearch也是严格遵循幂等性概念,每次数据更新,version+1

消费端-幂等性保障
在海量订单产生的业务高峰期,如何避免消息的重复消费问题?
消费实现幂等性,就意味着,我们的消息永远不会消费多次,即使我们收到了多条一样的消息

业界主流的幂等性操作

唯一ID+指纹码机制,利用数据库主键去重
唯一ID+指纹码机制,利用数据库主键去重
Select count(1) from T_order where ID=唯一ID+指纹码
好处:实现简单
坏处:高并发下有数据库写入的性能瓶颈
解决方案:根据ID进行分库分表进行算法路由

利用Redis的原子性去实现
使用Redis进行幂等,需要考虑的问题
第一:我们是否要进行数据落库,如果落库的话,关键解决的问题是数据库和缓存如何做到原子性?
第二:如果不进行落库,那么都存储到缓存中,如何设置定时同步策略?

3、Confirm确认消息

Confirm消息确认机制
消息的确认,是指生产者投递消息后,如果Broker收到消息,则会给我们生产者 一个应答。
生产者进行接收应答,用来确定这条消息是否正常的发送到Broker,这种方式也是消息的可靠性投递的核心保障

在这里插入图片描述

实现Confirm确认消息
第一步:在Channel上开启确认模式:channel.confirmSelect()
第二步:在channel上添加监听:addConfirmListener,监听成功和失败的返回结果,根据具体的结果对消息进行重新发送、或记录日志等后续处理!

消费者:

package com.hsl.rabbitmqapi.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @author water
 * @site www.water.com
 * @company xxx公司
 * @create 2020-02-29 11:18
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        //1 创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.1.31");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2 获取C    onnection
        Connection connection = connectionFactory.newConnection();

        //3 通过Connection创建一个新的Channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.#";
        String queueName = "test_confirm_queue";

        //4 声明交换机和队列 然后进行绑定设置, 最后制定路由Key
        channel.exchangeDeclare(exchangeName, "topic", true);
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);

        //5 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, queueingConsumer);

        while (true) {
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());

            System.err.println("消费端: " + msg);
        }


    }
}

生产者:

package com.hsl.rabbitmqapi.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * @author water
 * @site www.water.com
 * @company xxx公司
 * @create 2020-02-29 11:21
 */
public class Producer {
    public static void main(String[] args) throws Exception {
        //1 创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.1.31");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2 获取C    onnection
        Connection connection = connectionFactory.newConnection();

        //3 通过Connection创建一个新的Channel
        Channel channel = connection.createChannel();


        //4 指定我们的消息投递模式: 消息的确认模式
        channel.confirmSelect();

        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.save";

        //5 发送一条消息
        String msg = "Hello RabbitMQ Send confirm message!";
        channel.basicPublish(exchangeName, routingKey, null, msg.getBytes());

        //6 添加一个确认监听
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("-------no ack!-----------");
            }

            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("-------支付微服务ack!-----------");
            }
        });
    }

}

在这里插入图片描述
在这里插入图片描述

4、Return返回消息

Return Listener用于处理一些不可路由的消息!
正常情况:我们的消息生产者,通过指定一个Exchange和RoutingKey,把消息送达到某一个队列中去,然后我们的消费者监听队列,进行消费处理操作!

异常情况:在某些情况下,如果我们在发送消息的时候,当前的Exchange不存在或者指定的路由key路由不到,这个时候如果我们需要监听这种不可达的消息,就需要使用Return Listener!

在基础API中有一个关键的配置项
Mandatory:如果为true,则监听器会接收到路由不可达的消息,然后进行后续处理,如果为false,那么Broker端自动删除该消息!
在这里插入图片描述
消费者:

package com.hsl.rabbitmqapi.rabreturn;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @author water
 * @site www.water.com
 * @company xxx公司
 * @create 2020-02-29 11:23
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.1.31");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        String exchangeName = "test_return_exchange";
        String routingKey = "return.#";
        String queueName = "test_return_queue";

        channel.exchangeDeclare(exchangeName, "topic", true, false, null);
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);

        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        channel.basicConsume(queueName, true, queueingConsumer);

        while(true){
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.err.println("消费者: " + msg);
        }

    }

}

生产者:

package com.hsl.rabbitmqapi.rabreturn;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author water
 * @site www.water.com
 * @company xxx公司
 * @create 2020-02-29 11:26
 */
public class Producer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.1.31");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        String exchange = "test_return_exchange";
        String routingKey = "return.save";
        String routingKeyError = "abc.save";

        String msg = "Hello RabbitMQ Return Message";


        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange,
                                     String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {

                System.err.println("---------handle  return----------");
                System.err.println("replyCode: " + replyCode);
                System.err.println("replyText: " + replyText);
                System.err.println("exchange: " + exchange);
                System.err.println("routingKey: " + routingKey);
                System.err.println("properties: " + properties);
                System.err.println("body: " + new String(body));
            }
        });

        //消息投递成功,会被消费者所消费
//        channel.basicPublish(exchange, routingKey, true, null, msg.getBytes());
        //消息不可达,将触发ReturnListener
        channel.basicPublish(exchange, routingKeyError, true, null, msg.getBytes());
    }

}

在这里插入图片描述
在这里插入图片描述

5、自定义消费者

我们一般就是在代码中编写while循环,进行consumer.nextDelivery方法进行获取下一条消息,然后进行消费处理!
但是我们使用自定义的Consumer更加的方便,解耦性更加的强,也是实际工作中最常用的使用方式!

自定义消费者:

package com.hsl.rabbitmqapi.consumer;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * @author water
 * @site www.water.com
 * @company xxx公司
 * @create 2020-02-29 11:27
 */
public class MyConsumer extends DefaultConsumer {


    public MyConsumer(Channel channel) {
        super(channel);
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        System.err.println("-----------consume message----------");
        System.err.println("consumerTag: " + consumerTag);
        System.err.println("envelope: " + envelope);
        System.err.println("properties: " + properties);
        System.err.println("body: " + new String(body));
    }

}

消费者:

package com.hsl.rabbitmqapi.consumer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author water
 * @site www.water.com
 * @company xxx公司
 * @create 2020-02-29 11:29
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.1.31");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();


        String exchangeName = "test_consumer_exchange";
        String routingKey = "consumer.#";
        String queueName = "test_consumer_queue";

        channel.exchangeDeclare(exchangeName, "topic", true, false, null);
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);

        channel.basicConsume(queueName, true, new MyConsumer(channel));


    }

}

生产者:

package com.hsl.rabbitmqapi.consumer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author water
 * @site www.water.com
 * @company xxx公司
 * @create 2020-02-29 11:30
 */
public class Producer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.1.31");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        String exchange = "test_consumer_exchange";
        String routingKey = "consumer.save";

        String msg = "Hello RabbitMQ Consumer Message";

        for(int i =0; i<5; i ++){
            channel.basicPublish(exchange, routingKey, true, null, msg.getBytes());
        }

    }

}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

AI时代,程序员何去何从?别慌,看完这篇你就明白了 AI时代程序员的发展方向 摘要:随着AI代码助手的普及,程序员行业面临变革。本文通过实际案例展示AI写代码的能力与局限:AI能生成基础功能代码(如RESTful API、数据处理脚本),但缺乏业务理解、系统设计和复杂逻辑处理能力。程序员的核心价值在于需求分析、架构设计、性能优化等高层能力。未来程序员应: 掌握AI工具提升效率 专注于创新和架构设计 培养业务理解能力 持续学习新技术 AI不会取代程序员,但会淘汰不会使用AI的程序员。建议开发者拥抱AI工具,将其作为助手而非威胁,聚焦高价值工作。 阅读详情

相关推荐

【python快速编程入门(第二版)黑马程序员课后编程题】

python快速编程入门(第二版)黑马程序员课后编程题

weixin_46167259的博客 1万+

RabbitMQ支持消息的模式

当有多个消费者时,我们的消息会被哪个消费者消费呢,我们又该如何均衡消费者消费信息的多少呢?根据消费者的消费能力进行公平分发,处理快的处理的多,处理慢的处理的少;一个消费者一条,按均分配;

qq_44299529的博客 1741

嵌入式状态机编程-QP状态机框架与常见状态机方法

状态机基本术语 现态:是指当前所处的状态。 条件:又称为“事件”,当一个条件被满足,将会触发一个动作,或者执行一次状态的迁移。 动作:条件满足后执行的动作。动作执行完毕后,可以迁移到新的状态,也可以仍旧保持原状态。动作不是必需的,当条件满足后,也可以不执行任何动作,直接迁移到新状态。 次态:条件满足后要迁往的新状态。“次态”是相对于“现态”而言的,“次态”一旦被激活,就转变成新的“现态”了。 传统有限状态机Fsm实现方法 如图,是一个定时计数器,计数器存在两种状态,一种为设置状态,一种为计时状态 设

qq_36969440的博客 9661

【消息队列】RabbitMQ五种消息模式

Spring AMQP是基于AMQP协议定义的一套API规范,提供了模板来发送和接收消息,包含两部分,其中Spring-amqp是基础抽象,spring-rabbit是底层的默认实现。这是为了防止消息队列中的队列不存在,在进行消息队列初始化的时候不知道是先建立消费者,还是先建立生产者,所以都执行创建函数,但是创建的队列只有一个不会重复。发布者发送消息时,指定消息的RoutingKey,Exchange将消息路由到BindingKey与消息RoutingKey一致的队列。Work queue,工作队列。

weixin_62513677的博客 3505

从‘查理复用’到TM52F1363:深入剖析5脚188数码管的驱动原理与避坑指南

本文深入解析了5脚188数码管的驱动原理,重点介绍了查理复用技术如何通过5个IO引脚高效驱动188段显示,并详细探讨了TM52F1363单片机的寄存器配置与驱动实现。文章还提供了常见问题的解决方案和性能优化技巧,帮助开发者避免实际应用中的各种陷阱。

weixin_29159441的博客 477

Android 音频源码分析——AudioTrack设备选择

Android 音频源码分析——AndroidRecord录音(一) Android 音频源码分析——AndroidRecord录音(二) Android 音频源码分析——AndroidRecord音频数据传输流程 Android 音频源码分析——audioserver启动 Android 音频源码分析——AudioFlinger Android 音频源码分析——AudioTrack设备选择 基于Andorid9.0源码 以AudioTrack为例,梳理下输出设备选择流程。 音频设备选择的影响因素: Au

奋斗的菜鸟ing 3970

rabbitMQ的五种消息模式

rabbitMQ的五种消息模式

m0_63086385的博客 1521

在WPS/Office中免费使用AI,快速提升办公效率!​

《免费解锁WPS/Office AI办公神器教程》摘要: 本教程详解如何通过第三方插件OfficeAI免费实现WPS/Office智能办公,突破官方付费限制。从安全设置到安装配置,手把手教学,涵盖文档生成、PPT美化、Excel图表等核心功能。关键优势包括零成本、全场景支持及云端/本地双模式切换,并附常见问题解决方案。注意需使用WPS 2024+版本,安装时需临时关闭杀毒软件。教程强调工具来源合法性,建议商用购买正版授权。(149字)

杜哥无敌的博客 2302

RabbitMQ之消息模式简单易懂,超详细分享~~~

业务遇上对的消息模式很重要

zyq025的专栏 5670

【YOLOv11改进- 主干网络】YOLOv11+RepViT: 从ViT的角度重新审视Mobile的CNN助力YOLOv11有效涨点;

本文给大家带来的改进内容是在YOLOv11中更换主干网络为RepViT,助力YOLOv11有效涨点,论文通过集成轻量级 ViT 的高效架构设计,逐步增强了标准轻量级 CNN(即 MobileNetV3)的移动友好性。这最终产生了一个新的纯轻量级 CNN 系列的主干网络。

qq_41304809的博客 785

移动机器人路径规划中噪声环境下的鲁棒性测试仿真

设计一个二维或三维环境模型,包括静态障碍物和可能存在的动态障碍物。

amy_mhd的博客 125

RabbitMQ五种消息模式

介绍: Rabbit总共用6种消息模式,基本消息模式,工作模式,发布订阅模式,路由模式,主题模式,还有最后一种就是RPC,所有消息模式都是基于 基本消息模式进行的 :关于基本消息模式可以看我上一篇博客:https://blog.csdn.net/gloamer/article/details/118436062?spm=1001.2014.3001.5501 工作模式: 基本消息模式 就是说 一个消息生产者 一个消息队列 一个消息消费者,但消息过多,消费不过来,可能会导致消息堆积,所以当一个消费者..

gloamer的博客 5619

OSError We couldn‘t connect to https://huggingface.co to load file, couldn‘t find it chatglm3-6b解决方案

本文主要介绍了OSError: We couldn’t connect to https://huggingface.co to load this file, couldn’t find it in the cached files and it looks like THUDM/chatglm3-6b is not the path to a directory containing a file named config.json.解决方案,希望能对学习python的同学们有所帮助。

weixin_43178406的博客 5万+

【RabbitMQ】万字整理RabbitMQ的五种消息模式

RabbitMQ的五种消息模式(含代码示例)

m0_66584716的博客 1193

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

【RabbitMQ】消息模式

1、总览 在上一篇文章,已经讲述了RabbitMQ的核心组成部分。这里贴一张图: Producer通过Connection里的Channel发送信息到Exchange,Exchange把信息发送给它通过一定规则绑定的Queue,Consumer从Queue里获取信息。 其中Producer发送信息必须通过交换机发送,所以这里说一下Exchange的类型,和接下来要写的消息模式有关系。 交换机主要分为 fanout、direct、topic、header四种类型。接下来要讲的消息模式中,Simple和Wor

weixin_40794189的博客 272

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Go实现RabbitMQ消息模式

go实现RabbitMQ简单模式和work工作模式 go实现RabbitMQ 消息持久化和手动应答 go实现RabbitMQ 发布订阅模式 go使用MQ实现评论后排行榜更新

zwl153910的博客 1900

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

rabbitmq的消息模式

rabbitmq的消息模式(message pattern) rabbitmq的消息模型是基于交换器(exchange),队列(queue)和它们之间的绑定(bingdings),有以下几种: For point-to-point communication between the publisher and the broker, you can use a default or a dire...

面朝大海,春暖花开 1786

RabbitMQ深度探索:五种消息模式

消费模式

SOS_suyan的博客 1032

RabbitMQ从入门到入土——五种核心消息模式

RabbitMQ五种核心消息模式 相关概念 ​ 首先先了解下RabbitMQ中的相关概念,这里以五种消息模式中的路由模式为例: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uMYDs7Kr-1592365180053)(https://raw.githubusercontent.com/iszhonghu/Picture-bed/master/img/20200615102520.png)] 标志 名称 描述 P 生产者 消息的发送者,可以将消息发送到交换机

冢狐的私人空间 740

RabbitMQ的5种核心消息模式

文章目录简介相关概念安装访问配置5种消息模式简单模式工作模式发布/订阅模式路由模式通配符模式 简介 RabbitMQ是最受欢迎的开源消息中间件之一,在全球范围内被广泛应用。RabbitMQ是轻量级且易于部署的,能支持多种消息协议。RabbitMQ可以部署在分布式系统中,以满足大规模、高可用的要求。 相关概念 以消息模式中的路由模式为例 安装 此文只讲诉linux下安装的步骤 下载rabbitmq 3.7.15的Docker镜像 docker pull rabbitmq:3.7.15 使用Dock

weixin_39387961的博客 409

RabbitMQ之消息模式简单易懂,超详细分享

前言上一篇对RabbitMQ的流程和相关的理论进行初步的概述,如果小伙伴之前对消息队列不是很了解,那么在看理论时会有些困惑,这里以消息模式为切入点,结合理论细节和代码实践的方式一起来学习。正文常用的模式有Simple、Work、Fanout、Direct、Topic、Headers,可以通过设置交换机类型和配置参数来实现各个模式;接下来就分别进行实操演示吧。以下演示都是通过管理员的账号进行。其实每...

dotNET跨平台 453

RabbitMQ的5种核心消息模式都不懂,也敢说会用消息队列

此文转载自:https://my.oschina.net/u/4664854/blog/4767886 大咖揭秘Java人都栽在了哪?点击免费领取《大厂面试清单》,攻克面试难关~>>> 摘要 以前看过的关于RabbitMQ核心消息模式的文章都是基于JavaAPI的,最近看了下官方文档,发现这些核心消息模式都可以通过Spring AMQP来实现。于是总结了下Rabb...

Python研究所 404

rabbitmq消息模式

1.简单模式: P : 生产者 Queue(hello) : 队列 C : 消费者 步骤: 1.创建工程 2.分别添加RabbitMQ依赖 3.编写生产者发送消息 4.编写消费者获取消息 pom.xml <dependencies> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-cli...

Zmy_Admin的博客 886

RabbitMQ的消息模式和高级特性

配置优化spring:rabbitmq:# 连接池配置cache:channel:size: 50 # 缓存 Channel 数量checkout-timeout: 10000 # 获取 Channel 超时mode: channel # 缓存模式size: 10 # 缓存连接数# 连接超时# 心跳超时代码层面优化@Bean// 使用 JSON 序列化// 开启批量发送// 批量确认处理});@Bean// 并发消费者配置// 预取数量。

qq_38261626的博客 1098
上一篇: RabbitMQ的初步使用与交换机
下一篇: RabbitMQ的消息模式2
water_java
博客等级 码龄7年 9粉丝 124原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值